Why does pool run the entire file multiple times?

后端 未结 4 1179
南方客
南方客 2020-12-19 06:46

I\'m trying to understand the output from this Python 2.7.5 example script:

import time
from multiprocessing import Pool

print(time.strftime(\'%Y-%m-%d %H:%         


        
4条回答
  •  温柔的废话
    2020-12-19 07:24

    Python imports the __main__ module for each process. On an import, the whole file is executed again. On python 3, if you remove the if __name__ == '__main__' you will get an infinite loop since the file is getting recursively called.

    For the real question:

    In python scripts, I typically try to avoid executing any statements or variables on the global scope except for function definitions. I use the below as a template for all python scripts.

    import sys
    
    def main(argv):
      #main logic here
    
    if __name__ == '__main__':
      main(sys.argv)
    

    When you have a script with re-usable functions, even if it has a main method, you can import it into another script if you need to.

提交回复
热议问题