Request UAC elevation from within a Python script?

前端 未结 11 666

I want my Python script to copy files on Vista. When I run it from a normal cmd.exe window, no errors are generated, yet the files are NOT copied. If I run

11条回答
  •  悲&欢浪女
    2020-11-22 05:32

    Recognizing this question was asked years ago, I think a more elegant solution is offered on github by frmdstryr using his module pywinutils:

    Excerpt:

    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    
    

    This utilizes the COM interface and automatically indicates that admin privileges are needed with the familiar dialog prompt that you would see if you were copying into a directory where admin privileges are required and also provides the typical file progress dialog during the copy operation.

提交回复
热议问题