Calling if __name__ == '__main__': in one module from a function in another module [closed]

夙愿已清 提交于 2019-12-01 23:34:48

The if __name__ == '__main__' is mainly used to make a single python script executable. For instance, you define a function that does something, you use it by importing it and running it, but you also want that function to be executed when you run your python script with python module1.py.

For the question you asked, the best I could come up with is that you wanted a function defined in "module1.py" to run when you invoke "module2.py". That would be something like this:

### module1.py:
def main():
    # does something
    ...

if __name__ == '__main__':
    main()

### module2.py:
from module1 import main as main_from_module_one

if __name__ == '__main__':
    main_from_module_one()  # calling function main defined in module1

The whole point of the if __name__... is that it's for things that are only needed when the module is executed as a script, ie exactly if it's not being imported from another class. So no, you don't need to do this.

Your explanation of why you can't put things into a function make no sense; that is exactly what you should do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!