Is python script aware of its saved location path?

/home/bar/foo/test.py: 

I try test.py print /home/bar/foo no matter where I run the script from:

 import os def foo(): print os.getcwd() 

test run:

 [/home/bar $] python /home/bar/foo/test.py # echoes /home/bar [/tmp $] python /home/bar/foo/test.py # echoes /tmp 

os.getcwd() Not a function for the task. How can I do this otherwise?

+3
python
source share
6 answers

Try the following:

 import os.path p = os.path.abspath(__file__) 
+7
source share

The __file__ variable will contain the location of a separate Python file.

+2
source share

If the script is somewhere in your path, then yes, you can remove it from sys.argv

 #!/usr/bin/env python import sys import os print sys.argv print os.path.split(sys.argv[0]) dan@somebox:~$ test.py ['/home/dan/bin/test.py'] ('/home/dan/bin', 'test.py') 
+2
source share

As others have noted, you can use the __file__ attribute for module objects.

Although, I would like to note that in the general case, non-Python, case, you could use sys.argv[0] for the same purpose. This is the usual convention between different shells to pass the complete absolute path of the program through argv[0] .

0
source share

Put this in a file and then run it.

 import inspect, os.path def codepath(function): path = inspect.getfile(function) if os.path.isabs(path): return path else: return os.path.abspath(os.path.join(os.getcwd(), path)) print codepath(codepath) 

My tests show that this prints the absolute path of the Python script, whether it is run with the absolute path or not. I also successfully tested it when importing from another folder. The only requirement is that the function or equivalent call be present in the file.

0
source share
 import sys print sys.path[0] 

This will give you the full path to your script each time, while __file__ will provide you with the path that was used to execute the script. 'sys.path' always has the path to the script as the first element, which allows you to always be able to import other .py files into the same directory.

0
source share

All Articles