[英]Using stdout and stdin in a loop in python leading to errors
我正在使用 stdout 和 stdin 在兩個 python 程序之間傳遞信息。 tester.py 應該將遙測數據傳遞給 helper.py,helper.py 應該向 tester.py 返回一些命令。
這在沒有循環的情況下運行時似乎有效,但是當我將 tester.py 中的代碼放入更新遙測數據的循環中時,helper.py 似乎不再能夠傳回正確的命令。 控制台打印輸出如下:
b'\x00\x00\x00\x00\x01\x00\x00\x00'
0.0
b''
Traceback (most recent call last):
File "/Users/Advay/Documents/PyCharm/zip_sim/tester.py", line 44, in <module>
varr = COMMAND_STRUCT.unpack(cmd)
struct.error: unpack requires a buffer of 8 bytes
測試者.py:
import sys
import subprocess
import struct
TELEMETRY_STRUCT = struct.Struct(">fB3s")
COMMAND_STRUCT = struct.Struct(">fB3s")
helper = subprocess.Popen(['python3', 'helper.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
drop = 1
padding = bytes(3)
for i in range(5):
speed = i
helper.stdin.write(TELEMETRY_STRUCT.pack(speed, drop, padding))
helper.stdin.flush()
cmd = helper.stdout.read(COMMAND_STRUCT.size)
print(cmd)
varr = COMMAND_STRUCT.unpack(cmd)
print(varr[0])
和 helper.py:
import os
import random
import sys
import struct
TELEMETRY_STRUCT = struct.Struct(">fB3s")
COMMAND_STRUCT = struct.Struct(">fB3s")
telemetry = sys.stdin.buffer.read(TELEMETRY_STRUCT.size)
a = TELEMETRY_STRUCT.unpack(telemetry)
command = COMMAND_STRUCT.pack(a[0], 1, bytes(3))
sys.stdout.buffer.write(command)
sys.stdout.buffer.flush()
任何幫助將不勝感激,我完全不知道為什么。 在循環中不起作用。
您正在嘗試從tester.py
向helper.py
發送多個命令,但helper.py
只讀取一個命令然后退出——沒有循環允許它繼續從tester.py
接收其他命令。
運行tester.py
,第一次循環迭代成功,但后續迭代失敗,因為helper.stdout.read()
返回空值(因為助手已退出)。
您需要構建您的helper.py
以便它可以接收多個命令。
例如:
import os
import random
import sys
import struct
TELEMETRY_STRUCT = struct.Struct(">fB3s")
COMMAND_STRUCT = struct.Struct(">fB3s")
while True:
telemetry = sys.stdin.buffer.read(TELEMETRY_STRUCT.size)
if not telemetry:
break
a = TELEMETRY_STRUCT.unpack(telemetry)
command = COMMAND_STRUCT.pack(a[0], 1, bytes(3))
sys.stdout.buffer.write(command)
sys.stdout.buffer.flush()
通過此更改,運行tester.py
導致:
b'\x00\x00\x00\x00\x01\x00\x00\x00'
0.0
b'?\x80\x00\x00\x01\x00\x00\x00'
1.0
b'@\x00\x00\x00\x01\x00\x00\x00'
2.0
b'@@\x00\x00\x01\x00\x00\x00'
3.0
b'@\x80\x00\x00\x01\x00\x00\x00'
4.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.