In Python, can I call the main() of an imported module?

后端 未结 6 2017
时光取名叫无心
时光取名叫无心 2020-11-29 17:36

In Python I have a module myModule.py where I define a few functions and a main(), which takes a few command line arguments.

I usu

6条回答
  •  自闭症患者
    2020-11-29 17:57

    It depends. If the main code is protected by an if as in:

    if __name__ == '__main__':
        ...main code...
    

    then no, you can't make Python execute that because you can't influence the automatic variable __name__.

    But when all the code is in a function, then might be able to. Try

    import myModule
    
    myModule.main()
    

    This works even when the module protects itself with a __all__.

    from myModule import * might not make main visible to you, so you really need to import the module itself.

提交回复
热议问题