pythonpython-module

How to get filename of the __main__ module in Python?


Suppose I have two modules:

a.py:

import b
print __name__, __file__

b.py:

print __name__, __file__

I run the "a.py" file. This prints:

b        C:\path\to\code\b.py
__main__ C:\path\to\code\a.py

Question: how do I obtain the path to the __main__ module ("a.py" in this case) from within the "b.py" library?


Solution

  • import __main__
    print(__main__.__file__)