As of 2017, an easy way to achieve this is as follows:
import ctypes, sys def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin():
If you are using Python 2.x, you should replace the last line:
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(__file__), None, 1)
Also note that if you converted the python script to an executable file (using tools such as py2exe , cx_freeze , pyinstaller ), you must replace the fourth parameter with an empty string ( "" ).
Here are some of the benefits:
- No external libraries are required (as well as the Python extension for Windows). It uses only
ctypes from the standard library. - Works on both Python 2 and Python 3.
- There is no need to modify file resources or create a manifest file.
- If you do not add the code below, if / else, the code will never be executed twice.
- You can easily change it to have special behavior if the user rejects the UAC invitation.
- You can specify arguments that change the fourth parameter.
- You can specify a display method that changes the sixth parameter.
The documentation for the main ShellExecute call is here .
Martín De la Fuente Jan 30 '17 at 7:10 2017-01-30 07:10
source share