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

问题描述

大家好,

我想使用 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',help='Have the camera follow the zip in the y axis')
visualizer_group.add_argument('--show-lidar',help='Shows lidar in the visualization')
visualizer_group.add_argument('--start-paused',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() 来读取程序,但这只是挂起程序。有谁知道如何解决这个问题?感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)