Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of a running Python script?

Tags:

python

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.

like image 610
tehryan Avatar asked Sep 20 '09 06:09

tehryan


People also ask

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.

What is __ file __ in Python?

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.

How do I find the hostname of a Python window?

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.


3 Answers

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

like image 142
John Machin Avatar answered Sep 18 '22 15:09

John Machin


>> 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])
like image 23
Michael Foukarakis Avatar answered Oct 26 '22 09:10

Michael Foukarakis


Use

thisFile = __file__

It's magic!

like image 22
Charles Ritchie Avatar answered Oct 26 '22 11:10

Charles Ritchie