简体   繁体   中英

Python - Subprocess with STDIN and STDOUT

I would like to pass a byte-object from file A.py to B.py where it is incremented by 1 and then passed back. Currently I have the following code and whenever I run python A.py , the program does not print anything. I feel like the problem is in file B.py though I am not sure.

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()

In B.py you didn't specify how many bytes to read. It defaults to reading until it gets EOF, which won't happen until A.py closes the pipe.

So either close the pipe in A.py after writing (replace door.stdin.flush() with close(door.stdin) , or have B.py just read the number of bytes it needs.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM