The Artima Developer Community
Sponsored Link

Python Answers Forum
how to determine script directory?

3 replies on 1 page. Most recent reply: Aug 9, 2005 5:29 AM by Elizabeth Wiethoff

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
anh decent

Posts: 1
Nickname: anhdecent
Registered: Oct, 2003

how to determine script directory? Posted: Oct 9, 2003 5:19 PM
Reply to this message Reply
Advertisement
Anyone knows how to determine which directory the running script is in? Let's say foo.py prints out the directory it is in...and let's say that foo.py is in /AA/BB/ directory. Let's assume that directory /AA/BB/ is in the path, and I am currently at the root directory. If I execute foo.py from the root directory, foo.py would print out "/AA/BB/". Anyone knows how to implement that?

Yes, I am a Python beginner. :-)


Mike Huffman

Posts: 1
Nickname: mhuffman
Registered: Aug, 2003

Re: how to determine script directory? Posted: Oct 10, 2003 5:22 PM
Reply to this message Reply
Try this:


import sys, os

print 'sys.argv[0] =', sys.argv[0] # script name (for testing)
print 'os.getcwd() =', os.getcwd() # where we are (for testing)

print 'script running from', os.path.dirname(sys.argv[0])


If the above truncates the path, try this instead:


import sys, os, string

# walk the system PATH
for d in ( string.split(os.getenv('PATH'), os.pathsep) ):

# if this script (argv[0]) exists in a path directory, it must be the
# script that is executing
if os.path.exists(d + os.sep + os.path.basename(sys.argv[0])):
print sys.argv[0], "is running from", d

Jeffrey Ballagh

Posts: 1
Nickname: jballagh
Registered: May, 2005

Re: how to determine script directory? Posted: May 25, 2005 4:15 PM
Reply to this message Reply
Make it easier on yourself.

sys.path[0] returns the directory of the script that originally invoked the interpreter.

Try:
import sys

print 'sys.path[0] =', sys.path[0]

Elizabeth Wiethoff

Posts: 89
Nickname: ewiethoff
Registered: Mar, 2005

Re: how to determine script directory? Posted: Aug 9, 2005 5:29 AM
Reply to this message Reply
import os.path
os.path.dirname(__file__)

Flat View: This topic has 3 replies on 1 page
Topic: Python 2.1 and MySQL connection problem Previous Topic   Next Topic Topic: running btreannounce.py

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use