The Python Oracle

How do I get the path and name of the file that is currently executing?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 Question
00:52 Accepted answer (Score 279)
01:12 Answer 2 (Score 608)
01:31 Answer 3 (Score 101)
04:20 Answer 4 (Score 75)
05:10 Thank you

--

Full question
https://stackoverflow.com/questions/5049...

Question links:
[execfile]: http://docs.python.org/library/functions...

Answer 1 links:
[os.path.realpath]: https://docs.python.org/3/library/os.pat...

Answer 2 links:
[Difference between import and execfile]: https://stackoverflow.com/questions/2751...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #scripting #file

#avk47



ANSWER 1

Score 637


__file__

as others have said. You may also want to use os.path.realpath to eliminate symlinks:

import os

os.path.realpath(__file__)



ACCEPTED ANSWER

Score 287


p1.py:

execfile("p2.py")

p2.py:

import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory



ANSWER 3

Score 80


I think this is cleaner:

import inspect
print inspect.stack()[0][1]

and gets the same information as:

print inspect.getfile(inspect.currentframe())

Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.

print inspect.stack()[1][1]

would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.




ANSWER 4

Score 52


import os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only