Is a python script aware of its stored location path?
/home/bar/foo/test.py:
I am tryi开发者_StackOverflowng test.py
to print /home/bar/foo
irrespective of from 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 the function for the task. How can I get this done otherwise?
Try this:
import os.path
p = os.path.abspath(__file__)
The __file__
variable will contain the location of the individual Python file.
If the script is somewhere in your path, then yes, you can strip 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')
Place 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 an absolute path or not. I also tested it successfully when importing it from another folder. The only requirement is that a function or equivalent callable be present in the file.
As others have noted, you can use __file__
attribute of module objects.
Although, I'd like to note that in general, not-Python, case, you could've use sys.argv[0]
for the same purpose. It's a common convention among different shells to pass full absolute pathname of the program through argv[0]
.
import sys
print sys.path[0]
This will give you the full path to your script every time, whereas __file__
will give you the path that was used to execute the script. 'sys.path'
always has the path to the script as the first element, which allows one to always be able to import other .py files in the same directory.
精彩评论