1:如果调用的子进程也是一个python脚本,则subprocess.Popen中的bufsize=1无效果。也就是说,即使设置了bufsize=1表示进行行缓冲,子进程如果不显示调用sys.stdout.flush,父进程依然会阻塞在readline上:
#testbuf.py
importsubprocess
cmd= "./testsub.sh"cmd2= ["python", "testsub.py"]
sp= subprocess.Popen(cmd2, bufsize = 1, stdout =subprocess.PIPE)whileTrue:
line=sp.stdout.readline()print 'read line is', lineif not line: break
testsub.py代码如下:
importtimeimportsysfor i in range(100000):print 'hello, world', i#sys.stdout.flush()
time.sleep(1)
执行testbuf.py脚本,该脚本将会阻塞在sp.stdout.readline()上,除非将子进程testsub杀掉,否则,该脚本将会长时间阻塞在这条语句上。
如果将testsub.py中的sys.stdout.flush()前注释去掉,则父进程可以得到正常的输出。
如果执行的是shell脚本testsub.sh,则没有这种问题,该脚本代码如下:
#!/bin/bashfor((i=1;i<=1