How to run python script with elevated privilege on windows

前端 未结 11 1378
臣服心动
臣服心动 2020-11-22 07:34

I am writing a pyqt application which require to execute admin task. I would prefer to start my script with elevate privilege. I am aware that this question is asked many ti

11条回答
  •  名媛妹妹
    2020-11-22 08:01

    Here is a solution with an stdout redirection:

    def elevate():
        import ctypes, win32com.shell.shell, win32event, win32process
        outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
        if ctypes.windll.shell32.IsUserAnAdmin():
            if os.path.isfile(outpath):
                sys.stderr = sys.stdout = open(outpath, 'w', 0)
            return
        with open(outpath, 'w+', 0) as outfile:
            hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
                lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
            while True:
                hr = win32event.WaitForSingleObject(hProc, 40)
                while True:
                    line = outfile.readline()
                    if not line: break
                    sys.stdout.write(line)
                if hr != 0x102: break
        os.remove(outpath)
        sys.stderr = ''
        sys.exit(win32process.GetExitCodeProcess(hProc))
    
    if __name__ == '__main__':
        elevate()
        main()
    

提交回复
热议问题