python - 子进程 popen : Why do all writes happen at once in child process?

标签 python subprocess 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()。

最佳答案

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/

相关文章:

python - Python 微服务如何在授权 header 中使用 JWT 验证请求?

python - 如何在装饰器中捕获异常但允许调用者也捕获它?

python - 如何使这个列表反转算法更高效 python

python - 在python中将整数转换为二进制

python - 用 Python 编写的反向 shell 脚本的 Rust 等价物是什么?

python - 使用 shlex 的 Python 子进程 chmod 上出现无效模式错误

python - 如何在Python中检查视频是否有声音?

c - 无法使用 scanf 两次扫描字符串然后扫描字符

c - 在 C 中存储包含整数和字符的文件内容

input - 在 Go 中,使用递归扫描一行中的数字