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

Question:

I have 4 python script files.

  • script_1.py
  • script_2.py
  • script_3.py
  • script_4.py

script_1.py, script_2.py and script_3.py calls script_4.py

Execute files always change.

Like, python script_1.py / python script_2.py / python script_3.py

I want to get script_1.py, script_2.py, and script_3.py file name in script_4.py 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 script_4.py.

Asked By: Hyuntae Kim

||

Answers:

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

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

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