pythonpywin32

Why my "try/except" block misses the error?


I've been researching how to make my python code relaunch with admin privileges and was able to find the answer as:

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)

In the case when I grant the privileges in context Windows pop-up (i.e. "Do you want to allow this app to make changes to your device?") everything works fine, but when I select an option not to do so, the output console gives me an error 'pywintypes.error: (1223, 'ShellExecuteEx', 'The operation was canceled by the user.')', which makes total sense.

So I tried to catch this error by adding try/except block as:

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

Seems about right, however, I'm still getting the same error, in other words, "except ..." line doesn't work. I can solve this issue by replacing it with "except Exception", but I know it's a bad practice to do so and I'm really curious why it doesn't work... Any suggestions how it can be fixed? Thanks in advance.

Edit - adding full traceback of the error

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