How to import a module as __main__?

后端 未结 7 1129
借酒劲吻你
借酒劲吻你 2021-01-17 16:04

I have a module that has the usual

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

idiom.

I\'d like to import that from another module

相关标签:
7条回答
  • 2021-01-17 16:22

    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.

    0 讨论(0)
  • 2021-01-17 16:26

    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"))
    
    0 讨论(0)
  • 2021-01-17 16:34

    Put it in a function:

    def _main():
       do stuff
    
    if __name__ == '__main__':
        main()
    
    0 讨论(0)
  • 2021-01-17 16:36

    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()
    
    0 讨论(0)
  • 2021-01-17 16:37

    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__")
    
    0 讨论(0)
  • 2021-01-17 16:39

    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.

    0 讨论(0)
提交回复
热议问题