Sometimes, we want to request UAC elevation from within a Python script.
In this article, we’ll look at how to request UAC elevation from within a Python script.
How to request UAC elevation from within a Python script?
To request UAC elevation from within a Python script, we call ctypes.windll.shell32.ShellExecuteW
.
For instance, we write
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# ...
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
to define the is_admin
to check if the current user has admin permission with
ctypes.windll.shell32.IsUserAnAdmin()
If is_admin
returns False
, then we run the script again with
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
to run runas
with the script path and the command line arguments for the script.
Conclusion
To request UAC elevation from within a Python script, we call ctypes.windll.shell32.ShellExecuteW
.