How can I get first executing file name in different script in python?


I have 4 python script files.

  •, and calls

Execute files always change.

Like, python / python / python

I want to get,, and file name in python script.

How can I get current executing file name without having to pass that information as arguments?

I tried __name__ and inspect.getfile(inspect.currentframe()) but no luck.

Both of codes are returns

Asked By: Hyuntae Kim



You can use the module level attribute __file__ to get the path to the current module.

>>> import os
>>> os.path.basename(__file__)

If you want to determine this for another file, you can import the script and still query the value:

>>> import os
>>> import script1
>>> os.path.basename(script1.__file__)
Answered By: flakes

When called, sys.argv holds the command line arguments. The first element is the name of the script that was called (including path). To get the name of the script that was originally called you can do, in any of your files:

import os
import sys

called_script_with_path = sys.argv[0]
called_script_without_path = os.path.basename(sys.argv[0])
Answered By: Friedrich
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.