问题描述
我知道我可以使用例如pySerial 与串行设备通信,但是如果我现在没有设备但仍需要为其编写客户端怎么办?如何在 Python 中编写虚拟串行设备"并让 pySerial 与之对话,就像我会说,运行本地 Web 服务器一样?也许我只是没有很好地搜索,但我一直无法找到有关此主题的任何信息.
I know that I can use e.g. pySerial to talk to serial devices, but what if I don't have a device right now but still need to write a client for it? How can I write a "virtual serial device" in Python and have pySerial talk to it, like I would, say, run a local web server? Maybe I'm just not searching well, but I've been unable to find any information on this topic.
推荐答案
这是我迄今为止为我所做和解决的问题:
this is something I did and worked out for me so far:
import os, pty, serial
master, slave = pty.openpty()
s_name = os.ttyname(slave)
ser = serial.Serial(s_name)
# To Write to the device
ser.write('Your text')
# To read from the device
os.read(master,1000)
如果你创建更多的虚拟端口,你不会有问题,因为不同的 master 得到不同的文件描述符,即使它们具有相同的名称.
If you create more virtual ports you will have no problems as the different masters get different file descriptors even if they have the same name.
这篇关于Python中的虚拟串行设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!