Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a module as __main__?

Tags:

python

I have a module that has the usual

if __name__ == '__main__':
    do stuff...

idiom.

I'd like to import that from another module, and fool it into running that code. Is there any way of doing this?

I should mention, for reasons I won't go into here, I'm not in a position to change the code in the imported module. I need to somehow modify the import procedure so that it's name is main when imported, perhaps using ihooks or similar.

like image 674
xorsyst Avatar asked Jun 22 '12 16:06

xorsyst


2 Answers

As pointed out in the other answers, this is a bad idea, and you should solve the issue some other way.

Regardless, the way Python does it is like this:

import runpy
result = runpy._run_module_as_main("your.module.name"))
like image 148
mic_e Avatar answered Sep 19 '22 14:09

mic_e


The correct answer has been already given however it is confined in a comments (see How to import a module as __main__? and How to import a module as __main__?).

The same with proper formatting:

import runpy
runpy.run_module("your.module.name", {}, "__main__")

or

import runpy
runpy.run_path("path/to/my/file.py", {}, "__main__")
like image 24
acapola Avatar answered Sep 19 '22 14:09

acapola