inWaiting爵士()在读取虚拟p时总是返回0

2024-09-27 07:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难用虚拟端口玩得很好。我知道这是其他人写过的一个领域,但我在这些答案中找不到任何能解决我问题的东西。原谅我,如果我只是在说,解决方案已经在别处准备好了。你知道吗

这就是我试图实现的目标:我想设置一个虚拟端口,我可以在一个.py文件中写入数据,然后从中读取另一个.py文件中的数据。这是为了开发和测试的目的;我并不总是能够访问构建当前项目的设备。你知道吗

这是我目前的代码:

假人_序列号.py你知道吗

import os, pty, serial, time

master, slave = pty.openpty()
m_name = os.ttyname(master)
s_name = os.ttyname(slave)

# This tells us which ports "openpty" has happened to choose.
print("master: "+m_name)
print("slave: "+s_name)

ser = serial.Serial(s_name, 9600)

message = "Hello, world!"
encoded = message.encode("ascii")

while True:
  ser.write(encoded)
  time.sleep(1)

你知道吗阅读器.py你知道吗

import serial, time

# The port will change, depending on what port "openpty" (in the other file)
# happens to choose.
ser = serial.Serial("/dev/pts/1", 9600)

while True:
  time.sleep(1)
  incoming_bytes = ser.inWaiting()
  # This print statement gives us an idea of what's going on.
  print(incoming_bytes)
  if incoming_bytes != 0:
    data = ser.read(incoming_bytes)
    print(data)

现在,笨蛋_序列号.py看起来还不错。但是,阅读器.py只是一直说没有等待读取的字节,因此不读取任何数据。你知道吗

我想要的是:

  • 一个解释ser.inWaiting()为什么一直返回0,一个解决方案使得ser.read(x)实际上吐出“你好,世界!”你知道吗
  • 解释为什么我要做的从根本上说是愚蠢的,这是创建可写/可读虚拟端口的更好方法。你知道吗

Tags: 数据端口namepymasterbytestimeos

热门问题