截至2023年2月19日的更新
下面脚本的更新现在已经由同一作者制作成了Python包。您可以从PyPi安装它,PyPi的链接为https://pypi.org/project/pyuac/,源代码/主页位于https://github.com/Preston-Landers/pyuac。使用以下命令进行安装:
pip install pyuac
pip install pypiwin32
该包的直接使用方法是:
import pyuac
def main():
print("Do stuff here that requires being run as an admin.")
input("Press enter to close the window. >")
if __name__ == "__main__":
if not pyuac.isUserAdmin():
print("Re-launching as admin!")
pyuac.runAsAdmin()
else:
main()
或者,如果您想使用装饰器:
from pyuac import main_requires_admin
@main_requires_admin
def main():
print("Do stuff here that requires being run as an admin.")
input("Press enter to close the window. >")
if __name__ == "__main__":
main()
原始答案
谢谢大家的回复。我使用Preston Landers在2010年编写的模块/脚本让我的脚本正常工作了。在浏览了两天互联网后,我找到了这个脚本。它深藏在pywin32邮件列表中。使用此脚本可以更轻松地检查用户是否为管理员,如果不是,可以请求UAC /管理员权限。它提供了单独的窗口输出以显示代码正在执行的内容。此脚本还包括如何使用代码的示例。为了惠及所有正在寻找Windows上UAC的人,请查看此代码。可以像下面这样从您的主要脚本中使用:
import admin
if not admin.isUserAdmin():
admin.runAsAdmin()
实际的代码(在模块中)是:
import sys, os, traceback, types
def isUserAdmin():
if os.name == 'nt':
import ctypes
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print "Admin check failed, assuming not an admin."
return False
elif os.name == 'posix':
return os.getuid() == 0
else:
raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api, win32con, win32event, win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType,types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas'
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
else:
rc = None
return rc
def test():
rc = 0
if not isUserAdmin():
print "You're not an admin.", os.getpid(), "params: ", sys.argv
rc = runAsAdmin()
else:
print "You are an admin!", os.getpid(), "params: ", sys.argv
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
sys.exit(0)
并将print
放在if
块内。 - Leonardo.Z