tags:

views:

168

answers:

2

Duplicate of: In Python, how do I get the path and name of the file that is currently executing?

I would like to find out the path to the currently executing script. I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored.

+1  A: 

How about using sys.path[0]

You can do something like
'print os.path.join(sys.path[0], sys.argv[0])'

http://docs.python.org/lib/module-sys.html

Epitaph
Unlikely to actually be correct -- the running script may not be the first item on the path. It could be in any of the locations on the PYTHONPATH. Further, if it was started with python -m someModule, then argv[0] isn't relevant, either.
S.Lott
@S.Lott - From the docs that Pat linked: "the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter." so it should be correct for what I want but I have decided to use os.path.abspath(__file__) :)
Ashy
+6  A: 

In Python, __file__ identifies the current Python file. Thus:

print "I'm inside Python file %s" % __file__

will print the current Python file. Note that this works in imported Python modules, as well as scripts.

Brian Clapper