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 th
The suggestions marked as best are all true if your script consists of only one file.
If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named foo.py):
import inspect
print inspect.stack()[-1][1]
Because the last thing ([-1]
) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).
Then in file bar.py if you import foo
it'll print bar.py, rather than foo.py, which would be the value of all of these:
__file__
inspect.getfile(inspect.currentframe())
inspect.stack()[0][1]