Requesting UAC Elevation in a Python Script
When executing Python scripts that require administrative privileges, it's necessary to handle User Account Control (UAC) in order to gain the required permissions. Here's how:
Method:
Python 2.x:
import ctypes, sys def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): # Code of your program here else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)
For Python 3.x, replace the last line with:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
Advantages:
The above is the detailed content of How Can I Request UAC Elevation for My Python Script?. For more information, please follow other related articles on the PHP Chinese website!