5

I have created a script that uses Esri's arcpy site package and it functions properly in a stand-alone environment. I am now trying to integrate this script into a toolbox to be run within an open ArcMap session and I am having trouble. In integrating this script I am using the tool structure that ESRI suggests... http://goo.gl/eesrV . The script I have created has information in the 'ToolData' folder that I need to access to run the script.

How do I locate the script's directory dynamically when running it in an open ArcMap session?

In my stand-alone script I use 'os.getcwd()'; this works because it returns the proper location of the script and I then know the structure around it. Whereas when incorporated as a script in a tool box on run within an ArcMap session 'os.getcwd()' returns the directory of the map document while the toolbox, script, and tool data are located where ever the user installed them and my script can't find this structure.

5
  • 5
    Have you tried sys.argv[0]? Feb 6, 2012 at 16:35
  • I think that would require the user to input the location in which they installed the toolbox every time they ran the script. It seems like there should be a better way. I install toolboxes in a common area and then forget about them. Feb 6, 2012 at 16:47
  • 4
    Have you tried it? sys.argv[0] returns the path of the currently running module (script). __file__ should also do the trick.
    – blah238
    Feb 6, 2012 at 17:45
  • 1
    Thanks Chad for the correct answer and thank you @blah238 for making me try it when I thought it wouldn't work. Feb 6, 2012 at 19:52
  • 1
    @JustinMayers - Great! I went ahead and put it in a answer, please mark it as accepted to close this question. Feb 6, 2012 at 22:20

2 Answers 2

7

Try sys.argv[0], on Windows it will return the full path to the currently running script.

4

Chad Cooper was correct in guiding me to the following statement to yield the scripts directory:

sys.argv[0] - gives full path and script name

or even more specifically to get just the location

os.path.dirname(sys.argv[0])

Thanks to @blah238 for forcing me to look at something I thought wouldn't work. For additional info I also found support on ESRI's website: http://goo.gl/Fv4T3

1
  • 1
    Nice job Justin. It takes something to own up to one's mistakes publicly. It would have been easy to sidle sideways with a meek "oh!". Your summary also added useful info not previously mentioned. Welcome to GIS.se! Feb 7, 2012 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.