Welcome, guest | Sign In | My Account | Store | Cart
1

As you can see in Windows Control Panel 'System' applet there are two groups of environment variables: USER and SYSTEM. Here presents function for retrieve SYSTEM variable value.

Python, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: Windows-1251 -*-
'''
getenv_system.py

Get SYSTEM environment value, as if running under Service or SYSTEM account

Author: Denis Barmenkov <denis.barmenkov@gmail.com>

Copyright: this code is free, but if you want to use it, 
           please keep this multiline comment along with function source. 
           Thank you.

2006-01-28 15:30
'''

import os, win32api, win32con

def getenv_system(varname, default=''):
    v = default
    try:
        rkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
        try:
            v = str(win32api.RegQueryValueEx(rkey, varname)[0])
            v = win32api.ExpandEnvironmentStrings(v)
        except:
            pass
    finally:
        win32api.RegCloseKey(rkey)
    return v

print 'SYSTEM.TEMP => %s' % getenv_system('TEMP')
print 'USER.TEMP   => %s' % os.getenv('TEMP')

It can be useful if you write some system utility, for sample, temporary files remover: with standard os.getenv('TEMP') you can clean user temp directory but with getenv_system() -- system temp dir too.

1 comment

Roger Erens 11 years, 3 months ago  # | flag

See also Microsoft's examples. Microsoft has quite a lot of useful examples available via

http://www.microsoft.com/technet/scriptcenter/scripts/python/default.mspx

An alternative way to look up (user/sytem/whatever) environment variables is given by

http://www.microsoft.com/technet/scriptcenter/scripts/python/desktop/explorer/dmexpy03.mspx

which uses an SQL-ish way.

Add a comment

Sign in to comment