Python 标准输入/标准输出读取

时间:2021-04-02 17:52:21

标签: python struct subprocess pipe communication

大家好,

我想使用 stdin/stdout 子进程管道在两个 python 脚本“Test1.py”和“Test2.py”之间进行通信。 Test1.py 写入标准输入,而 test2.py 从标准输入读取。 Test2.py 写入标准输出,而 test1.py 从标准输出读取。我可以从 test2.py 写入标准输出,然后读取 test1.py 中的标准输出并打印结果。那部分工作。但是,如果我尝试在 test1.py 中写入 stdin 并在 test2.py 中读取 stdin,则程序只会挂起并停止工作。这是我的 test1.py 脚本:

import argparse
import math
import os
import random
import sys
import subprocess
import struct

COMMAND_STRUCT = struct.Struct(">fB3s")
TELEMETRY_STRUCT = struct.Struct(">fB3s")


parser = argparse.ArgumentParser(description='"8-bit" Zip Sim')
parser.add_argument('pilot', nargs=argparse.REMAINDER, help='A pilot process to run')
parser.add_argument('--headless', action="store_true", help='Run without visualization')
visualizer_group = parser.add_argument_group("Visualization options")
visualizer_group.add_argument('--chase-y', action="store_true", help='Have the camera follow the zip in the y axis')
visualizer_group.add_argument('--show-lidar', action="store_true", help='Shows lidar in the visualization')
visualizer_group.add_argument('--start-paused', action="store_true", help='Start the simulation paused')

parser.add_argument('--seed', type=int, help='Seed to use for random number generation')
args = parser.parse_args()

random.seed(args.seed)
headless = args.headless
api_mode = len(args.pilot) > 0
    
if api_mode:
    pilot = subprocess.Popen(args.pilot, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    loop_count = 0  # To count iterations to compute the telemetry timestamp

pilot.stdin.write(TELEMETRY_STRUCT.pack(20.2,3,b'3s'))
pilot.stdin.flush()
loop_count += 1
cmd = pilot.stdout.read(COMMAND_STRUCT.size)
if len(cmd) != COMMAND_STRUCT.size:
    result = CRASHED  # The pilot process must have 
lateral_airspeed_input, drop_package_commanded_byte, _ = COMMAND_STRUCT.unpack(cmd)
lateral_airspeed = max(-30.0, min(30.0, lateral_airspeed_input))
#print("speed", lateral_airspeed_input)
#print("drop", drop_package_commanded_byte)
drop_package_commanded = bool(drop_package_commanded_byte)

现在这是我的 Test2.py 脚本:

import struct
import sys
import time

COMMAND_STRUCT = struct.Struct(">fB3s")
TELEMETRY_STRUCT = struct.Struct(">Hhffb31B")


packed_data = struct.pack(">fB3s",19.1,1,b'3s')
Telemetry = sys.stdin.read()
#print(telemetry, file = sys.stderr)

sys.stdout.buffer.write(packed_data)
sys.stdout.flush()

我正在使用 sys.stdin.read() 来读取程序,但这只是挂起程序。有谁知道如何解决这个问题?感谢您的帮助!

0 个答案:

没有答案
相关问题