How to import a module as __main__?

后端 未结 7 1131
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题