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?
__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.
For a pure python module you can find the source by looking at themodule. __file__ . The datetime module, however, is written in C, and therefore datetime.
The value of __name__ attribute is set to “__main__” when module is run as main program. Otherwise, the value of __name__ is set to contain the name of the module. We use if __name__ == “__main__” block to prevent (certain) code from being run when the module is imported.
import __main__ print(__main__.__file__)
Perhaps this will do the trick:
import sys from os import path print(path.abspath(str(sys.modules['__main__'].__file__)))
Note that, for safety, you should check whether the __main__
module has a __file__
attribute. If it's dynamically created, or is just being run in the interactive python console, it won't have a __file__
:
python >>> import sys >>> print(str(sys.modules['__main__'])) <module '__main__' (built-in)> >>> print(str(sys.modules['__main__'].__file__)) AttributeError: 'module' object has no attribute '__file__'
A simple hasattr() check will do the trick to guard against scenario 2 if that's a possibility in your app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With