-
-
Save HatScripts/2e90dc41b692d7b100643836ca974faf to your computer and use it in GitHub Desktop.
Elevate the privilege to admin. Support both python script and pyinstaller wrapped program. Need ctypes only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on Gary Lee's code: | |
# https://gist.github.com/GaryLee/d1cf2089c3a515691919 | |
# https://stackoverflow.com/a/33856172/2203482 | |
def run_as_admin(argv=None): | |
import ctypes | |
shell32 = ctypes.windll.shell32 | |
if argv is None and shell32.IsUserAnAdmin(): | |
return True | |
import sys | |
if argv is None: | |
argv = sys.argv | |
arguments = argv[1:] if hasattr(sys, "_MEIPASS") else argv | |
argument_line = " ".join(str(arg) for arg in arguments) | |
executable = str(sys.executable) | |
# Elevating to admin privileges... | |
ret = shell32.ShellExecuteW(None, "runas", executable, argument_line, None, 1) | |
if int(ret) <= 32: | |
raise IOError(f"Error(ret={ret}): Cannot elevate admin privileges.") | |
else: | |
return False | |
if __name__ == "__main__": | |
if run_as_admin(): | |
# Your code requiring admin privileges goes here, for example: | |
from pathlib import Path | |
Path("path/to/link").symlink_to(Path("path/to/target")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment