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

Question

Asked By – Ray

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let’s say I have three files. Using execfile:

  • script_1.py calls script_2.py.
  • In turn, script_2.py calls script_3.py.

How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py?

(Executing os.getcwd() returns the original starting script’s filepath not the current file’s.)

Now we will see solution for issue: How do I get the path and name of the file that is currently executing?


Answer

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

This question is answered By – Pat Notz

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0