才能運行具有管理員權限的腳本,我使用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? –