DumbledoreD
DumbledoreD

Reputation: 41

Request UAC Elevation From Within Python Script With ctypes.windll.shell32.ShellExecuteW

myClass generates a XLSX file to the './output' folder. The following line of code in myClass requires administrator privilege:

excel = win32com.client.Dispatch('Excel.Application')

I followed the answer in Request UAC elevation from within a Python script?, and now I have the following script:

import ctypes, sys
from my_module import myClass

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    myClass
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, "", None, 1)

However, this seems to elevate and exit, as if I selected No in the UAC prompt.

If I run the above code block in Administrator cmd, >python uac_test.py, somehow it generates 2 identical files, instead of one.

Am I missing something? Any help is appreciated!

Upvotes: 4

Views: 2589

Answers (1)

toti
toti

Reputation: 335

I believe myClass WAS executed, but in a separate window/process so you didn't notice.

try using something like input() to see if another window was indeed open.

Upvotes: 1

Related Questions