python - 如何让多处理运行?
问题描述
我试图让两个进程同时运行,而不是一次运行一个。我的代码如下。有人可以告诉我有什么问题吗?谢谢!
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。他们中的任何一个都应该工作。
推荐阅读
- math - Perlin 噪声不同的实现
- python - scrapy python中的Unicode问题
- xamarin.forms - Xamarin 表单输入框使用自定义键盘丢失光标位置
- asp.net-core - Visual Studio 2019 Net 5 ASP.NET Core WebApp 错误 MSB3644 .NETFramework,Version=v5.0 的参考程序集未找到
- jquery - When user select 2 then two select box and input field will show and when 3 is selected then ONLY three select box and input fields is show
- javascript - 在页面加载方面是否可以加载js文件并在客户端使用js创建整个页面
- linux - 如何仅将缺少的参数添加到配置文件?
- python - 如何在 Windows 上使用来自 Python 数组的内容创建文件?
- ceph - ceph fs mds 卡在 `up:rejoin` 状态 - `未能打开 ino 0x101 err -116/0`
- angular - 将模板投影到Angular中的远方后代