Python - 带有 STDIN 和 STDOUT 的子进程

问题描述

我想将一个字节对象从文件 A.py 传递到 B.py,在那里它增加 1,然后传回。目前我有以下代码,每当我运行 python A.py 时,程序都不会打印任何内容。虽然我不确定,但我觉得问题出在文件 B.py 中。

A.py

import subprocess
import struct

door = subprocess.Popen(['python','B.py'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
door.stdin.write(struct.pack(">B",0))
door.stdin.flush()
print(struct.unpack(">B",door.stdout.read()))

B.py

import sys
import struct

my_input = sys.stdin.buffer.read()
nbr = struct.unpack(">B",my_input)
sys.stdout.buffer.write(struct.pack(">B",nbr+1))
sys.stdout.buffer.flush()

解决方法

B.py 中,您没有指定要读取的字节数。它默认为读取直到获得 EOF,直到 A.py 关闭管道才会发生这种情况。

所以要么在写入后关闭 A.py 中的管道(将 door.stdin.flush() 替换为 close(door.stdin),或者让 B.py 只读取它需要的字节数。

my_input = sys.stdin.buffer.read(struct.calcsize(">B"))