subprocess: stdin.write 后 stdout.readline随机卡顿
设置了一个subprocess.Popen去执行指令。
self.pipe = subprocess.Popen([self.app,self.pid_address],stdin=subprocess.PIPE,stdout=subprocess.PIPE,close_fds=True,bufsize=0,universal_newlines=True)
主程序:
self.pipe.stdin.write('%s\n' % command)
print ("after write "+time.strftime("%y-%m-%d %H:%M:%S\n"))
time.sleep(0.05)
results = self.pipe.stdout.readline().strip() ## 此处随机卡顿
print ("after results "+time.strftime("%y-%m-%d %H:%M:%S\n"))
但是指令总是随机卡顿。比如循环执行50次主程序,
可能20次很快,但是第21次,35次会卡几秒或者十几秒。
通过打印发现, 应该是在pipe.stdin.write结束之后。 应该就是在执行self.pipe.stdin.write(‘%s\n’ % command)
results = self.pipe.stdout.readline().strip()。
但是添加 sleep 0.05 毫秒可以明显减少卡顿次数,但是无法根除。可能频率下降30%或50%。
感觉和buffer啥的有关。但是如果使用communicate()是不行的。因为调用的第三方程序不会退出,导致在pipe.communicate()一直卡住。
目前只能用stdin.write 和stdout.readline
请问有啥建议呀?
It will be better if with simple, short and executable code to demo your issue to people may help.