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
This should work:
import os,sys
filename=os.path.basename(os.path.realpath(sys.argv[0]))
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))
Here is what I use so I can throw my code anywhere without issue. __name__
is always defined, but __file__
is only defined when the code is run as a file (e.g. not in IDLE/iPython).
if '__file__' in globals():
self_name = globals()['__file__']
elif '__file__' in locals():
self_name = locals()['__file__']
else:
self_name = __name__
Alternatively, this can be written as:
self_name = globals().get('__file__', locals().get('__file__', __name__))
The __file__
attribute works for both the file containing the main execution code as well as imported modules.
See https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__
__file__
as others have said. You may also want to use os.path.realpath to eliminate symlinks:
import os
os.path.realpath(__file__)
Try this,
import os
os.path.dirname(os.path.realpath(__file__))
It's not entirely clear what you mean by "the filepath of the file that is currently running within the process".
sys.argv[0]
usually contains the location of the script that was invoked by the Python interpreter.
Check the sys documentation for more details.
As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to
the file from which the module was loaded, if it was loaded from a file