我试图让两个进程同时运行,而不是一次运行一个。我的代码如下。有人能告诉我怎么了吗?谢谢
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.
您应该刷新多处理位中的输出流。您可以将flush=True
添加到打印语句中,将sys.stdout.flush()
添加到函数末尾,将单个print("", flush=True)
添加到函数结尾,或者在从命令行调用程序时指定-u
参数(python -u your_file_name.py
(。后者以"无缓冲"模式运行python。它们中的任何一个都应该起作用。