才能运行具有管理员权限的脚本,我使用ctypes.windll.shell32.ShellExecuteW
。我不想用win32api
,因为这是一个需要安装,其中不包。我已经意识到,使用下面的脚本(简体),如果脚本是在一个目录中运行在一个空格(如“C:\用户\用户\ Documents \我的文件夹”),即使UAC请求被批准,该脚本不会获得管理员权限。只要脚本没有在名称中有空格的目录中执行,它就可以正常工作。为什么Python UAC Request不适用于其中有空格的路径?
脚本:
# Name of script is TryAdmin.py
import ctypes, sys, os
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
print("I'm an Admin!")
input()
else:
b=ctypes.windll.shell32.ShellExecuteW(None,'runas',sys.executable,os.getcwd()+'\\TryAdmin.py',None,1)
if b==5: # The user denied UAC Elevation
# Explain to user that the program needs the elevation
print("""Why would you click "No"? I need you to click yes so that I can
have administrator privileges so that I can execute properly. Without admin
privileges, I don't work at all! Please try again.""")
input()
while b==5: # Request UAC elevation until user grants it
b=ctypes.windll.shell32.ShellExecuteW(None,'runas',sys.executable,os.getcwd()+'\\TryAdmin.py',None,1)
if b!=5:
sys.exit()
# else
print('Try again!')
input()
else:
sys.exit()
这有什么错SYS? –