windows系统内,如何在py文件执行时提升管理员权限运行?
方法一
1、新建go.cmd脚本文件,脚本内加入vbs提权代码启动cmd窗口。
2、然后在cmd窗口运行py程序,内容如下。
@echo off
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
cd /d "%~dp0"
start python LoadDiabloII.py
方法二
直接在目标py文件内加入代码。
1、增加当前py文件是否是以管理员权限执行的判断函数。
from __future__ import print_function
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
2、在主函数 if __name__ == "__main__": 中修改代码如下。
if is_admin():
# 将要运行的代码加到这里
else:
if sys.version_info[0] == 3:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
else:#in python2.x
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(__file__), None, 1)
4万+

被折叠的 条评论
为什么被折叠?



