Reputation: 8237
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.
Upvotes: 17
Views: 11814
Reputation: 1243
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__")
Upvotes: 5
Reputation: 5830
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"))
Upvotes: 20
Reputation: 35059
Put it in a function:
def _main():
do stuff
if __name__ == '__main__':
main()
Upvotes: -1
Reputation: 9581
There is, execute the script instead of importing it. But I consider this an extremely hackish solution.
However the ideal pattern would be:
def do_stuff():
... stuff happens ...
if __name__ == '__main__':
do_stuff()
that way you can do:
from mymodule import do_stuff
do_stuff()
EDIT: Answer after clarification on not being able to edit the module code.
I would never recommend this in any production code, this is a "use at own risk" solution.
import mymodule
with open(os.path.splitext(mymodule.__file__)[0] + ".py") as fh:
exec fh.read()
Upvotes: 9
Reputation: 10685
Here is an example of a main module in Python:
#! /usr/bin/env python
import sys
import os
def main(arg1, arg2, arg3):
print(arg1, arg2, arg3)
if __name__ == "__main__":
main(*sys.argv)
But you can also include
def main():
#The module contains Python code specific to the library module,
#like tests, and follow the module with this:
if __name__ == "__main__":
main(*sys.argv)
in any module you would like to run as main.
For example, if you have a library module, you can always use this construct to execute something specific like tests.
Upvotes: 0
Reputation: 798456
Code in a main stanza usually never makes sense to run directly. If you want to run it then use subprocess
to run it in another Python interpreter.
Upvotes: 1
Reputation: 88977
Put that code in a function, and call it from the module you are importing it into as well.
def stuff():
...
if __name__ == '__main__':
stuff()
And then in the module you are importing it into:
import module
module.stuff()
Upvotes: 3