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
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.
To get directory of executing script
print os.path.dirname( inspect.getfile(inspect.currentframe()))
if you want just the filename without ./
or .py
you can try this
filename = testscript.py
file_name = __file__[2:-3]
file_name
will print testscript
you can generate whatever you want by changing the index inside []
import os
print os.path.basename(__file__)
this will give us the filename only. i.e. if abspath of file is c:\abcd\abc.py then 2nd line will print abc.py
I think it's just __file__
Sounds like you may also want to checkout the inspect module.
To keep the migration consistency across platforms (macOS/Windows/Linux), try:
path = r'%s' % os.getcwd().replace('\\','/')