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 order to get the script name:
print(Scriptname)
For getting the name of the Python script that is currently running you can use __file__. And if you want to remove the directory part which might be present with the name of the script, you can use os. path. basename(__file__).
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
You can use __file__
to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked.
If you want to omit the directory part (which might be present), you can use os.path.basename(__file__)
.
import sys print(sys.argv[0])
This will print foo.py
for python foo.py
, dir/foo.py
for python dir/foo.py
, etc. It's the first argument to python
. (Note that after py2exe it would be foo.exe
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With