How do I get the name of a running Python script?
I tried os.__file__
but that returns the name of the file where os
resides.
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.
The __file__ variable: __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.
Use the gethostname() Method to Find the Hostname of a Machine in Python. The gethostname() function is used to return a string containing the machine's hostname value on which the Python interpreter is currently executing.
It depends on what you mean by "a running python script".
__file__
will give you the name of the currently executing file. If that's a module, you'll get where it was imported from e.g. blahblah.pyc
sys.argv[0]
will give you the name of the script that is being run, even if called from a module that that script imported.
Please do look up the answers to the earlier question on this topic (see S.Lott's comment on your question).
>> import os
>> import sys
>> print sys.argv[0]
or if you just want the script and not the full path
>>
>> print os.path.basename(sys.argv[0])
Use
thisFile = __file__
It's magic!
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