Skip to content Skip to sidebar Skip to footer

Is A Python Script Aware Of Its Stored Location Path?

/home/bar/foo/test.py: I am trying 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

Solution 1:

Try this:

import os.path
p = os.path.abspath(__file__)

Solution 2:

The __file__ variable will contain the location of the individual Python file.

Solution 3:

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

#!/usr/bin/env python                                                           
import sys
import osprint sys.argv
printos.path.split(sys.argv[0])

dan@somebox:~$ test.py
['/home/dan/bin/test.py']
('/home/dan/bin', 'test.py')

Solution 4:

Place this in a file and then run it.

import inspect, os.path

def codepath(function):
  path = inspect.getfile(function)ifos.path.isabs(path): returnpathelse: returnos.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.

Solution 5:

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].

Post a Comment for "Is A Python Script Aware Of Its Stored Location Path?"