我有两个脚本,一个控制另一个并通过stdin与它通信。父脚本:子进程popen:为什么所有的写入都会在子进程中立即发生?
import subprocess
import time
p = subprocess.Popen(['python','read_from_stdin.py'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
for i in range(0,10):
p.stdin.write(str(i))
p.stdin.write('\r\n') # \n is not sufficient on Windows
p.stdin.flush()
print i
time.sleep(1)
p.stdin.close()
孩子脚本(称为“read_from_stdin.py”):
import sys
import datetime
with open(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.txt','w') as f:
for line in sys.stdin:
f.write(datetime.datetime.now().isoformat() + ' ' + line)
在那种年代由孩子脚本所有的输入具有相同的时间戳创建的文件,尽管被写入除了父脚本以外,尽管使用了flush()。
只想发表:) http://stackoverflow.com/questions/8416586/turn-off-buffering它*不*等待EOF,但有*缓冲*。请更新您的答案。 –
@ KarolyHorvath:它不等待EOF是正确的,但是你连接的问题是不相关的(修复'grep -line-buffered'在这里不起作用 - OP已经调用了p.stdin。齐平()')。问题是Python 2中的预读错误,在sys.stdin中有'for line。解决方法是:'对于行iter(sys.stdin.readline,'')' – jfs
@ J.F.Sebastian:*叹*。检查顶部投票答案... –