我希望我的Python脚本能够复制Vista上的文件。当我从一个普通的cmd.exe
窗口运行它时,不会产生任何错误,也不会复制文件。如果我“以管理员身份”运行cmd.exe
,然后运行我的脚本,它会工作得很好。
这是有意义的,因为用户帐户控制(UAC)通常会阻止许多文件系统操作。
有没有一种方法可以从Python脚本中调用UAC提升请求(那些对话框中会说“某某个应用程序需要管理员访问权限,这样可以吗?”)
如果这是不可能的,有没有办法让我的脚本至少检测到它没有被提升,这样它就可以优雅地失败?
发布于 2012-08-01 02:09:36
我花了一小段时间才弄明白dguaraglia的答案,所以为了节省其他人的时间,我做了以下工作来实现这个想法:
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
发布于 2019-10-23 07:55:46
只是添加这个答案,以防其他人像我一样被谷歌搜索引导到这里。我在Python脚本中使用了elevate
模块,并在Windows10中以管理员权限执行该脚本。
发布于 2015-08-26 23:03:37
认识到这个问题是几年前提出的,我认为frmdstryr使用他的模块pywinutils在github上提供了一个更优雅的解决方案:
摘录:
import pythoncom
from win32com.shell import shell,shellcon
def copy(src,dst,flags=shellcon.FOF_NOCONFIRMATION):
""" Copy files using the built in Windows File copy dialog
Requires absolute paths. Does NOT create root destination folder if it doesn't exist.
Overwrites and is recursive by default
@see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx for flags available
"""
# @see IFileOperation
pfo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation,None,pythoncom.CLSCTX_ALL,shell.IID_IFileOperation)
# Respond with Yes to All for any dialog
# @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx
pfo.SetOperationFlags(flags)
# Set the destionation folder
dst = shell.SHCreateItemFromParsingName(dst,None,shell.IID_IShellItem)
if type(src) not in (tuple,list):
src = (src,)
for f in src:
item = shell.SHCreateItemFromParsingName(f,None,shell.IID_IShellItem)
pfo.CopyItem(item,dst) # Schedule an operation to be performed
# @see http://msdn.microsoft.com/en-us/library/bb775780(v=vs.85).aspx
success = pfo.PerformOperations()
# @see sdn.microsoft.com/en-us/library/bb775769(v=vs.85).aspx
aborted = pfo.GetAnyOperationsAborted()
return success is None and not aborted
这利用COM接口,并通过熟悉的对话框提示自动指示需要管理员权限,如果要复制到需要管理员权限的目录,则会看到该提示,并且还在复制操作过程中提供典型的文件进度对话框。
https://stackoverflow.com/questions/130763
复制相似问题