简体   繁体   中英

How to import a module as __main__?

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.

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"))

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()

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()

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__")

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.

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.

Put it in a function:

def _main():
   do stuff

if __name__ == '__main__':
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM