arcpy.env.workspace = sys.path[0] gives different results in PythonWin - BUG?

2927
2
02-15-2013 04:10 PM
ChristiNelson1
Occasional Contributor
Hi all,

When I run the following snippet in PythonWin, the results come back with the correct location (C:\PSL\Scripts).  However, when this code is loaded into the ArcMap Python Window, the results are different and incorrect!  I will be sharing a tool that will be run from the Python Window in ArcGIS and I need to create a (correct) relative workspace for it.  Suggestions?

#import modules and define workspace
import arcpy
import os
import traceback
import sys

arcpy.env.workspace = sys.path[0]

print arcpy.env.workspace


When run in PythonWin, I get:

>>> C:\PSL\Scripts

When run in ArcMap Python Window, I get:

C:\WINDOWS\system32\python26.zip

I need ArcMap Python Window to return the same value as the value from PythonWin!!!

Im using ArcGIS 10 (ArcInfo level), Python26, Windows 7
Tags (2)
0 Kudos
2 Replies
T__WayneWhitley
Frequent Contributor
Sounds like you want the root where the script resides?

Then try:

import sys, os
arcpy.env.workspace = sys.argv[0].rsplit(os.sep, 1)[0]

-Wayne


EDIT:
sys.path
"If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules..."
http://docs.python.org/2/library/sys.html#sys.path

Based on that and similar wording for the .argv command the returned string could be 'empty' as well, meaning you do not have access to the script directory given the way you are running the script.  What you could do instead is test for an empty returned string on sys.argv[0], and instead write your results to a backup or common retrievable location.
0 Kudos
by Anonymous User
Not applicable
I just thought I would add here that this is not a bug.  Using the sys.path will return the PYTHONPATH, which as Wayne mentioned lists the paths that Python will search for when importing modules.  In addition to the PYTHONPATH, Python will also search the PYTHONHOME directory, which is the current working directory of the script being ran.

Here is another way to set the workspace to the directory of the script you are running:

import arcpy, os, sys

arcpy.env.workspace = os.path.dirname(sys.argv[0])
0 Kudos