Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which file was the "initiator" Python

Situation: We know that the below will check if the script has been called directly.

if __name__ == '__main__':
    print "Called directly"

else:
    print "Imported by other python files"

Problem: The else clause is only a generic one and will run as long as the script was not called directly.

Question: Is there any way to get which file it was imported in, if it is not called directly?

Additional information: Below is an example of how I envisioned the code would be like, just that I do no know what to put in <something>.

if __name__ == '__main__':
    print "Called directly"

elif <something> == "fileA.py":
    print "Called from fileA.py"

elif <something> == "fileB.py":
    print "Called from fileB.py"

else:
    print "Called from other files"
like image 447
Timothy Wong Avatar asked Oct 17 '22 23:10

Timothy Wong


2 Answers

Try this:-

import sys
print sys.modules['__main__'].__file__

Refer for better answer:- How to get filename of the __main__ module in Python?

like image 143
AlokThakur Avatar answered Oct 21 '22 04:10

AlokThakur


There are a couple different methods you may like to be aware of depending on what you're trying to accomplish.

The inspect module has a getfile() function which can be used to determine the name of the currently-executing function.

Example:

#!/usr/bin/env python3
import inspect
print(inspect.getfile(inspect.currentframe()))

Result:

test.py

To find out which command-line arguments were used to execute a script, you'll need to use sys.argv

Example:

#!/usr/bin/env python3
import sys
print(sys.argv)

Result when invoked with ./test.py a b c:

['./test.py', 'a', 'b', 'c']

Result when invoked with python3 test.py a b c:

['test.py', 'a', 'b', 'c']

Hope this helps!

like image 38
Max Avatar answered Oct 21 '22 05:10

Max