我有两个脚本,一个控制另一个并通过标准输入与之通信。父脚本:
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()。
最佳答案
是the read-ahead bug in Python 2 : for line in sys.stdin:
在其内部缓冲区已满之前不会产生任何结果。使用 for line in iter(sys.stdin.readline, ''):
来解决它。
关于python - 子进程 popen : Why do all writes happen at once in child process?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957432/