Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
Roman Starkov Avatar asked Mar 03 '09 14:03

Roman Starkov


People also ask

What is __ main __ file in Python?

__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.

How do I find the source of a Python module?

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.

What will be the value of __ name __ attribute of the imported module?

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.


2 Answers

import __main__ print(__main__.__file__) 
like image 196
ironfroggy Avatar answered Sep 22 '22 07:09

ironfroggy


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.

like image 36
Jarret Hardie Avatar answered Sep 24 '22 07:09

Jarret Hardie