Possible Duplicate:
Retrieving python module path
python, path of script
I have a Python file, and I would like to parse the path when this file is executed. If I run myPython.py like this:
python ~/Documents/Project/myPython.py
I would like to know the path “~/Documents/Project/” in the file myPython.py.
sys.argv[0]is the path of your script as executed by Python. You can useos.path.dirname()to get just the directory name from that:It is OS-dependent if it is the full path entered on the command line; Mac OS X and Linux both include the path.
The path can, however, differ based on how Python invoked it. An alternative is to use
__file__, and you can make the path absolute by usingos.path.abspath()andos.path.expanduser()to cover all variations: