Search code examples
pythonpywin32uac

Why doesn't my "try/except" block catch this error?


To make my Python code relaunch with admin privileges:

import sys
import os
from win32comext.shell import shell


asadmin = 'asadmin'
if sys.argv[-1] != asadmin:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [asadmin])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)

When I grant the User Account Control (UAC) prompt everything works. When I decline, the output console gives me:

pywintypes.error: (1223, 'ShellExecuteEx', 'The operation was canceled by the user.')

I tried to catch this error:

import ctypes
import sys
import os
from win32comext.shell import shell
from win32ctypes.pywin32 import pywintypes # Importing pertinent module

try:
    if sys.argv[-1] != asadmin:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script] + sys.argv[1:] + [asadmin])
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
        sys.exit(0)
except pywintypes.error:
    pass

I'm still getting the same error (except doesn't work). Replacing with except Exception is bad practice and I'm curious why it doesn't work. How can it be fixed?

Traceback:

Traceback (most recent call last):
  File "C:\Users\....myproject.py", line 13, in <module>
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
pywintypes.error: (1223, 'ShellExecuteEx', 'The operation was canceled by the user.')

Solution

  • Most probably, you are using the wrong import

    Try importing it directly like

    import pywintypes