[英]Only one process prints in unix, multiprocessing python
I have a script where I'm loading a file which takes a while because there is quite much data to read and to prevent the user from terminating the process I want to show some kind of loading indication. 我有一个脚本,我正在加载一个文件,这需要一段时间,因为有很多数据要读取,并防止用户终止我希望显示某种加载指示的过程。 I thought this was a good opportunity to learn how to use the multiprocessing module so I wrote this example to test the module: 我认为这是学习如何使用多处理模块的好机会,所以我写了这个例子来测试模块:
import time, multiprocessing
def progress():
delay = 0.5
while True:
print "Loading.",
time.sleep(delay)
print "\b.",
time.sleep(delay)
print "\b.",
time.sleep(delay)
print "\r \r",
return
def loader(filename, con):
# Dummy loader
time.sleep(5)
con.send(filename)
con.close()
return
if __name__ == "__main__":
parrent_con, child_con = multiprocessing.Pipe()
filename = "main.key"
p1 = multiprocessing.Process(target=progress)
p2 = multiprocessing.Process(target=loader, args=(filename, child_con))
p1.start()
p2.start()
data = parrent_con.recv()
p1.terminate()
print "\n", data
It works as I expect when I run it in windows cmd, it prints "Loading" and sequentially adds dots until the loader is complete. 当我在windows cmd中运行它时,它可以正常工作,它会打印“正在加载”并按顺序添加点,直到加载程序完成。 But in unix where I need it to work I don't get any output from progress function, process p1. 但是在我需要它工作的unix中,我没有从进度函数,进程p1获得任何输出。
Just as Mark and Dacav suggested, buffering is the problem. 正如Mark和Dacav所说,缓冲就是问题所在。 Here are some possible solutions: 这是一些可能的解决方案:
Using python -u
to run the script 使用python -u
运行脚本
python -u
will unbuffer stdout and stderr. python -u
将unbuffer stdout和stderr。 This is the easiest solution if it's acceptable to you. 如果您可以接受,这是最简单的解决方案。
Using sys.stdout.flush
使用sys.stdout.flush
sys.stdout.flush
will flush the stdout from buffer. sys.stdout.flush
将从缓冲区刷新stdout。
delay = 0.5 while True: print("Loading."), sys.stdout.flush() time.sleep(delay) print("\\b."), sys.stdout.flush() time.sleep(delay) print("\\b."), sys.stdout.flush() time.sleep(delay) print("\\r \\r"), sys.stdout.flush() return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.