tags:

views:

75

answers:

3

sys.arg[0] gives me the python script. For example 'python hello.py' returns hello.py for sys.arg[0]. But I need to know where the hello.py is located in full path.

How can I do that with python?

+6  A: 
os.path.abspath(sys.argv[0])
leoluk
This will only work if you haven't called os.chdir yet.
sharth
+2  A: 

You can use __file__, a variable that contains the full path to the module from which you access it. This doesn't necessarily have to end with the ".py" extension, but can also be ".pyc" (or None).

There is also documentation available on __file__.

AndiDog
See info on the Module object's predefined attributes in the documentation here: http://docs.python.org/reference/datamodel.html#objects-values-and-types (the link in the answer is wrong).
martineau
+1  A: 
import sys
print(sys.path[0])

From the docs:

As initialized upon program startup, the first item of this list, sys.path[0], is the directory containing the script that was used to invoke the Python interpreter.

unutbu