Request UAC elevation from within a Python script?

前端 未结 11 647

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:41

    This is mostly an upgrade to Jorenko's answer, that allows to use parameters with spaces in Windows, but should also work fairly well on Linux :) Also, will work with cx_freeze or py2exe since we don't use __file__ but sys.argv[0] as executable

    import sys,ctypes,platform
    
    def is_admin():
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            raise False
    
    if __name__ == '__main__':
    
        if platform.system() == "Windows":
            if is_admin():
                main(sys.argv[1:])
            else:
                # Re-run the program with admin rights, don't use __file__ since py2exe won't know about it
                # Use sys.argv[0] as script path and sys.argv[1:] as arguments, join them as lpstr, quoting each parameter or spaces will divide parameters
                lpParameters = ""
                # Litteraly quote all parameters which get unquoted when passed to python
                for i, item in enumerate(sys.argv[0:]):
                    lpParameters += '"' + item + '" '
                try:
                    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, lpParameters , None, 1)
                except:
                    sys.exit(1)
        else:
            main(sys.argv[1:])
    

提交回复
热议问题