pythonpython-importfilereference

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"

Solution

  • Try this:-

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

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