views:

103

answers:

3

I'm writing a little program as a self-learning project in Python 3.x. My idea is for the program to allow two fields of text entry to the user, and then plug the user's input into the value of two specific registry keys.

Is there a simple way to make it check if the current user can access the registry? I'd rather it cleanly tell the user that he/she needs administrator privileges than for the program to go nuts and crash because it's trying to access a restricted area.

I'd like it to make this check as soon as the program launches, before the user is given any input options. What code is needed for this?

Edit: in case it isn't obvious, this is for the Windows platforms.

+4  A: 

Here's a short article on how to determine if an application requires elevated privileges.

You can use pywin32 or ctypes to do the CreateProcess() call.

I suggest ctypes since it comes standard in python now, and there is a good example of using CreateProcess with ctypes here.

Eloff
+1  A: 

Most straightforward way is try to change the key at the beginning, maybe to a stub value - if that fails, catch the error and tell the user.

nosklo
Depending on the situation this may clobber the value of an existing key, in which case you might need to read it first, save that value, try to change it, and be sure to set it back if it succeeds. That's fine an all, until someone hits ctrl-c or the power goes out between the last two steps. It's an easy solution with difficult edge cases.
Eloff
+1  A: 

With pywin32, something like the following should work...:

import pythoncom
import pywintypes
import win32api
from win32com.shell import shell

if shell.IsUserAnAdmin():
   ...

And yes, it seems pywin32 does support Python 3.

Alex Martelli