首页 > 解决方案 > 如何让多处理运行?

问题描述

我试图让两个进程同时运行,而不是一次运行一个。我的代码如下。有人可以告诉我有什么问题吗?谢谢!

from multiprocessing import Process
from os import getpid
from random import randint
from time import time, sleep

def download_task(filename):
    print('Initiate downloading task, task No.[%d].' % getpid())
    print('Begin downloading %s...' % filename)
    time_to_download = randint(5, 10)
    sleep(time_to_download)
    print('Finished downloading %s! It took %d seconds' % (filename, time_to_download))

def main():
    start = time()
    p1 = Process(target=download_task, args=('Python: from beginer to lunatic.pdf',))
    p1.start()
    p2 = Process(target=download_task, args=('Peking Hot.avi',))
    p2.start()
    p1.join()
    p2.join()
    end = time()
    print('It took %.2f seconds in total.' % (end - start))

if __name__ == '__main__':
    main()

现在,这就是我所得到的。

It took 0.14 seconds in total.

但我应该得到这样的东西:

Start downloading Python: from beginer to lunatic.pdf...
Start downloading Peking Hot.avi...
Finished downloading Python: from beginer to lunatic.pdf! It took 5 seconds
Finished downloading Peking Hot.avi! It took 5 seconds
It took 5.00 seconds in total.

标签: pythonmultiprocessing

解决方案


您应该刷新多处理位中的输出流。您可以通过添加flush=True到打印语句、添加sys.stdout.flush()到函数末尾、添加单个print("", flush=True)到函数末尾或-u在从命令行调用程序时指定参数 ( python -u your_file_name.py) 来执行此操作。后者以“无缓冲”模式运行 python。他们中的任何一个都应该工作。


推荐阅读