在 Windows 上以提升的权限运行脚本
应用程序开发中的许多任务需要提升的权限,特别是在与系统资源交互或执行管理操作时。本文解决了在 Python 中运行需要管理访问权限的脚本的具体问题。
挑战
提供的代码示例尝试使用提升的权限启动脚本。但是,该脚本永远不会超出权限提示。该问题似乎在于对脚本执行的常见误解。
解决方案
提供的代码基于这样的假设:它可以通过以管理员权限重新启动来进行自我提升。然而,由于 Windows 中特权操作的本质,这种方法并不可行。相反,我们必须利用外部机制来请求提升。
一个高效的解决方案是 Preston Landers 在 2010 年创建的一个综合脚本。该脚本使用户能够轻松检查当前用户是否具有管理权限,如果没有,请求 UAC 提升。该脚本在单独的窗口中提供视觉反馈,指示系统的操作。
使用 Preston Landers 脚本
可以使用以下代码片段将该脚本集成到您的主应用程序中:
import admin if not admin.isUserAdmin(): admin.runAsAdmin()
完整的脚本代码可以在下面找到:
#!/usr/bin/env python # -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4 # (C) COPYRIGHT © Preston Landers 2010 # Released under the same license as Python 2.6.5 import sys, os, traceback, types def isUserAdmin(): if os.name == 'nt': import ctypes # WARNING: requires Windows XP SP2 or higher! try: return ctypes.windll.shell32.IsUserAnAdmin() except: traceback.print_exc() print "Admin check failed, assuming not an admin." return False elif os.name == 'posix': # Check for root on 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],) # XXX TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL #showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # print "Running", cmd, params # ShellExecute() doesn't seem to allow us to fetch the PID or handle # of the process, so we can't get anything useful from it. Therefore # the more complex ShellExecuteEx() must be used. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) 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) #print "Process handle %s returned code %s" % (procHandle, rc) 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(["c:\Windows\notepad.exe"]) 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())
或者,您现在可以安装并使用此脚本作为 PyPi 中的 Python 包。请按照以下步骤操作:
- 使用 pip install pyuac 和 pip install pypiwin32 安装软件包。
- 像这样使用软件包:
import pyuac def main(): print("Do stuff here that requires being run as an admin.") # The window will disappear as soon as the program exits! input("Press enter to close the window. >") if __name__ == "__main__": if not pyuac.isUserAdmin(): print("Re-launching as admin!") pyuac.runAsAdmin() else: main() # Already an admin here.
或者,使用装饰器:
from pyuac import main_requires_admin @main_requires_admin def main(): print("Do stuff here that requires being run as an admin.") # The window will disappear as soon as the program exits! input("Press enter to close the window. >") if __name__ == "__main__": main()
以上是如何在 Windows 上以提升的权限运行 Python 脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!

Python的灵活性体现在多范式支持和动态类型系统,易用性则源于语法简洁和丰富的标准库。1.灵活性:支持面向对象、函数式和过程式编程,动态类型系统提高开发效率。2.易用性:语法接近自然语言,标准库涵盖广泛功能,简化开发过程。

Python因其简洁与强大而备受青睐,适用于从初学者到高级开发者的各种需求。其多功能性体现在:1)易学易用,语法简单;2)丰富的库和框架,如NumPy、Pandas等;3)跨平台支持,可在多种操作系统上运行;4)适合脚本和自动化任务,提升工作效率。

可以,在每天花费两个小时的时间内学会Python。1.制定合理的学习计划,2.选择合适的学习资源,3.通过实践巩固所学知识,这些步骤能帮助你在短时间内掌握Python。

Python适合快速开发和数据处理,而C 适合高性能和底层控制。1)Python易用,语法简洁,适用于数据科学和Web开发。2)C 性能高,控制精确,常用于游戏和系统编程。

学习Python所需时间因人而异,主要受之前的编程经验、学习动机、学习资源和方法及学习节奏的影响。设定现实的学习目标并通过实践项目学习效果最佳。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python在游戏和GUI开发中表现出色。1)游戏开发使用Pygame,提供绘图、音频等功能,适合创建2D游戏。2)GUI开发可选择Tkinter或PyQt,Tkinter简单易用,PyQt功能丰富,适合专业开发。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

SublimeText3汉化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

禅工作室 13.0.1
功能强大的PHP集成开发环境