Skip to main content

以管理员模式执行

以装饰器形式

def is_admin(fn):
@wraps(fn)
def run(*args, **key):
try:
import ctypes
if ctypes.windll.shell32.IsUserAnAdmin():

print('当前是管理员')
return fn(*args, **key)
else:
if DEBUG:
print('请使用管理员权限执行')
return
except:
return False

return run

以入口函数形式

def run_as_admin() -> bool:
import ctypes, sys

# UAC申请,获得管理员权限
try:
res = ctypes.windll.shell32.IsUserAnAdmin()

if res: return True

# 重调用自身
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
exit()
except Exception:
logging.error('发错错误,无法使用管理员模式重启脚本')
return False