How to find which file was the "initiator" of Python

Situation: we know that below we will check if the script call was directly.

if __name__ == '__main__': print "Called directly" else: print "Imported by other python files" 

Problem: the else clause is only general and will work until the script is called directly.

Question: Is there a way to get the file into which it was imported if it is not directly called?

Additional information: Below is an example of how I assumed that the code would be similar, I just don’t 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" 
+5
source share
2 answers

Try the following: -

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

Ask for the best answer: How to get __main__ file name in Python?

+2
source

There are several different methods that you might want to know, depending on what you are trying to accomplish.

The inspect module has a getfile() function that 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 the script, you need to use sys.argv

Example:

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

Result when calling ./test.py abc :

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

Result when calling python3 test.py abc :

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

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1274946/


All Articles