Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find path to currently running file

Tags:

python

How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:

$ pwd /tmp $ python baz.py running from /tmp  file is baz.py 
like image 275
Chris Bunch Avatar asked Aug 18 '09 21:08

Chris Bunch


People also ask

How do I find the current file path?

Run it with the python (or python3 ) command. You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .

How do you find the running path in Python?

How to Get Current Python Directory? To find out which directory in python you are currently in, use the getcwd() method. Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python.

What is __ file __ in Python?

The __file__ variable: __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.

How do I get the full path of a file in Python?

To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.


1 Answers

__file__ is NOT what you are looking for. Don't use accidental side-effects

sys.argv[0] is always the path to the script (if in fact a script has been invoked) -- see http://docs.python.org/library/sys.html#sys.argv

__file__ is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0].

Example:

C:\junk\so>type \junk\so\scriptpath\script1.py import sys, os print "script: sys.argv[0] is", repr(sys.argv[0]) print "script: __file__ is", repr(__file__) print "script: cwd is", repr(os.getcwd()) import whereutils whereutils.show_where()  C:\junk\so>type \python26\lib\site-packages\whereutils.py import sys, os def show_where():     print "show_where: sys.argv[0] is", repr(sys.argv[0])     print "show_where: __file__ is", repr(__file__)     print "show_where: cwd is", repr(os.getcwd())  C:\junk\so>\python26\python scriptpath\script1.py script: sys.argv[0] is 'scriptpath\\script1.py' script: __file__ is 'scriptpath\\script1.py' script: cwd is 'C:\\junk\\so' show_where: sys.argv[0] is 'scriptpath\\script1.py' show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc' show_where: cwd is 'C:\\junk\\so' 
like image 84
John Machin Avatar answered Sep 17 '22 08:09

John Machin