I\'m trying to get the name of the Python script that is currently running.
I have a script called foo.py
and I\'d like to do something like this in ord
You can do this without importing os or other libs.
If you want to get the path of current python script, use: __file__
If you want to get only the filename without .py extension, use this:
__file__.rsplit("/", 1)[1].split('.')[0]
My fast dirty solution:
__file__.split('/')[-1:][0]
os.path.abspath(__file__) will give you an absolute path (relpath()
available as well).
sys.argv[-1] will give you a relative path.
Note that __file__
will give the file where this code resides, which can be imported and different from the main file being interpreted. To get the main file, the special __main__ module can be used:
import __main__ as main
print(main.__file__)
Note that __main__.__file__
works in Python 2.7 but not in 3.2, so use the import-as syntax as above to make it portable.
If you're doing an unusual import (e.g., it's an options file), try:
import inspect
print (inspect.getfile(inspect.currentframe()))
Note that this will return the absolute path to the file.
For modern Python versions (3.4+), Path(__file__).name
should be more idiomatic. Also, Path(__file__).stem
gives you the script name without the .py
extension.