How to import a module as __main__?

后端 未结 7 1250
借酒劲吻你
借酒劲吻你 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: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()
    

提交回复
热议问题