import ctypes, sysdef is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return Falseif is_admin(): # Code of your program hereelse: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
如果你使用的是Python 2.x,则应将最后一行替换为:
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unipre(sys.executable), unipre(__file__), None, 1)
还要注意的是,如果你转换你的Python脚本到一个可执行文件(使用工具,如
py2exe,cx_freeze,pyinstaller),那么你应该更换第四个参数为空字符串(”“)。
这里的一些优点是:
- 不需要外部库(也不需要Python用于Windows扩展)。它仅从ctypes标准库使用。
- 适用于Python 2和Python 3。
- 无需修改文件资源或创建清单文件。
- 如果你不在if / else语句下添加代码,则该代码将永远不会执行两次。
- 如果用户拒绝UAC提示,则可以轻松地将其修改为特殊行为。
- 你可以指定参数来修改第四个参数。
- 你可以指定修改第六个参数的显示方法



