Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of current script in Python

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) 
like image 779
SubniC Avatar asked Nov 11 '10 09:11

SubniC


People also ask

How do I get the script name in Python?

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__).

What is __ name __ Python?

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.


2 Answers

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__).

like image 61
Sven Marnach Avatar answered Oct 23 '22 16:10

Sven Marnach


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.)

like image 31
Chris Morgan Avatar answered Oct 23 '22 14:10

Chris Morgan