Read time: 4 minutes

Have you ever wanted to write a script that saves a file to the current user's desktop? Do you want to find out how? Enjoy this week's Knowledge Base Nugget...

Q: How can I find the current User folders using Python?

Windows and Python Environment Variables - User Folders

Python is a full featured scripting language and has many functions to access system and environment variable found in higher level languages.

From the command line the setx DOS command can be used to set environment variables:

C:\>setx MYVAL 25.4

Starting a new command line dialog (CMD.EXE) the set DOS command can be then used to view the variable value:

C:\> set MYVAL
MYVAL=25.4

Python can also be used to retrieve and set environment variables, using the os module, from the Python command line:

>>> import os
>>> os.system('setx MYVAL 25.4')


Starting a new command dialog (CMD.EXE), you will be able to"see" the new variable, again using the DOS set command:

C:\>set MYVAL
MYVAL=25.4

Or the Python command line as well:

>>> import os
>>> print os.environ['MYVAL']

To see all the environment variables simply print the os.environ method...it returns a list:

>>> import os
>>> print os.environ

Current User Profile and Desktop Folder

To retrieve the path to the Current User's Folders use the 'USERPROFILE' variable in the os.environ call. As an example, to navigate to the desktop within GPSE (from a running Python script) simply append"/Desktop" to the returned value:

user_profile = os.environ['USERPROFILE']
user_desktop = user_profile +"/Desktop"

Helpful GPSE Script

Here is a useful environment script specifically for the GPSE:

#-*- coding: utf-8 -*-
#
# Sample startup utility script
#
# 1) Import all of Geomagic API
# 2) Create default"Directories" variables
# 3) Create a variable that points to the User's folder (.iniml file)
# 4) Check to see if the macro folder is in the system path (add it if not)
# 5) Get the currently running Geomagic application
# 6) Create variables for all of the Geomagic Public Documents folders
#
# prints results to stdout (Scripting Tab Output Window)
#
import os, sys, string, geoappall, geoapiall

for m in geoapiall.modules: exec"from %s import *" % m
for m in geoappall.execStrings: exec m in globals(), locals()

from geoapp.appdata import Directories

# create commonly used directory constants
MACRO_FOLDER = unicode( Directories.getDirectory(Directories.DIRECTORY_MACROS) )
OPEN_FOLDER = unicode( Directories.getDirectory(Directories.DIRECTORY_OPEN) )
SAVE_FOLDER = unicode( Directories.getDirectory(Directories.DIRECTORY_SAVE) )
PUBLIC_DOCS = unicode( Directories.getDirectory(Directories.DIRECTORY_DOCUMENTS_COMMON) )

# create a constant for the folder where the current user's parameter settings file is stored
# Usually for Win7 it is C:\Users\\AppData\Roaming\Geomagic
INIML_FOLDER = unicode( Directories.getDirectory(Directories.DIRECTORY_CONFIG) )

# If the macro folder is not in the current sys.path, then add it
if sys.path.count(MACRO_FOLDER) == 0:
sys.path = sys.path + [MACRO_FOLDER]

# Get the currently running geomagic application's path and executable name
currentExecutingApp = os.path.split(sys.executable)
CURRENT_EXE_PATH = unicode( currentExecutingApp[0] )
CURRENT_EXE_NAME = unicode( currentExecutingApp[1] )

#
# Create the Geomagic public folder constants for the currently running Geomagic application
#
# First define a function that will build a list of all the top level subdirectories of any given folder
def BuildSubFolderList(folder):
return [ d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)] if os.path.isdir(d) ]

# Then call that function and pass it the currently running Geomagic application's public docs folder
pubFolders = BuildSubFolderList( PUBLIC_DOCS +"\\" + os.path.split(CURRENT_EXE_PATH)[1] )

# Create constants for all public folders
for folder in pubFolders:
exec '%s ="%s"' % ( string.upper( string.replace( os.path.split(folder)[1],"","_") +"_FOLDER" ), string.replace( folder, '\\', '\\\\') )

##
## test the constants
##
print"Currently running: %s\nCURRENT_EXE_PATH: %s\nCURRENT_EXE_NAME: %s\n" % ( sys.executable, CURRENT_EXE_PATH, CURRENT_EXE_NAME )
print"Current User's setting file is:", INIML_FOLDER +"\\geomagic.iniml"
print"\nCurrent Public Documents Folders:\n"
print"\tCAPTURES_FOLDER:", CAPTURES_FOLDER
print"\tDATA_FOLDER:", DATA_FOLDER
print"\tLOGS_FOLDER:", LOGS_FOLDER
print"\tMACROS_FOLDER:", MACROS_FOLDER
print"\tMATERIALS_FOLDER:", MATERIALS_FOLDER
print"\tPDF_FOLDER:", PDF_FOLDER
print"\tREPORTS_FOLDER:", REPORTS_FOLDER
print"\tRIBBON_LAYOUT_FOLDER:", RIBBON_LAYOUT_FOLDER
print"\tRULES_FOLDER:", RULES_FOLDER
print"\tSAMPLE_DATA_FOLDER:", SAMPLE_DATA_FOLDER
print"\tSNAPSHOTS_FOLDER:", SNAPSHOTS_FOLDER
print"\tTEXTURES_FOLDER:", TEXTURES_FOLDER
print"\tTHEMES_FOLDER:", THEMES_FOLDER

print ("\nPython sys.path:\n")

for p in sys.path:
print"\t" + p

for ev in os.environ:
print ev,":", os.environ[ev]


print"sys.prefix:", sys.prefix
print"sys.meta_path:", sys.meta_path
print"sys.modules:", sys.modules
print"sys.path_hooks:", sys.path_hooks
print"sys.platform:", sys.platform
print"sys.version_info:", sys.version_info

##
## end test
##

More Advanced

More advanced techniques such as this snippet from ActiveState, use win32api and win32con to extract values of the system state directly from the Windows Registry:

# -*- coding: Windows-1251 -*-
'''
getenv_system.py

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

Author: Denis Barmenkov

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')