python - 在python的循环中使用stdout和stdin导致错误
问题描述
我正在使用 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
tester.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()
任何帮助将不胜感激,我完全不知道为什么。在循环中不起作用。
解决方案
您正在尝试从 to 发送多个命令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
推荐阅读
- c# - 使用带有 AnyAsync() 扩展的最小起订量到 GetAll()
- docker - docker-pr proc 已经在监听 80 端口了?在 Ubuntu 上使用 snappy 安装 docker
- python - 无法在我的数据中从字符串转换为 int 列
- python - 在 numpy 数组中找到很大的差异
- angular - 如何以角度将对象从一个组件传递到另一个组件
- java - (React Native/Android) Android getFilesDir() 给我 '/data/user/' 而不是 '/data/data/'
- python - TensorFlow 中类似 NumPy 的切片
- security - 为什么 Emacs 抱怨有风险的文件局部变量?
- powershell - 使用 powershell 进行敏感词搜索
- python - Igraph 绘图损坏节点名称