Python 如何使用 PySerial 从 COM 端口读取和写入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44056846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read and write from a COM Port using PySerial?
提问by Neil Dey
I have Python 3.6.1 and PySerial Installed. I am trying the
我安装了 Python 3.6.1 和 PySerial。我正在尝试
I am able to get the list of comports connected. I now want to be able to send data to the COM port and receive responses back. How can I do that? I am not sure of the command to try next.
我能够获得连接的通讯列表。我现在希望能够将数据发送到 COM 端口并接收响应。我怎样才能做到这一点?我不确定接下来要尝试的命令。
Code:
代码:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
Output:
输出:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
COM7 - 多产的 USB 到串行通信端口 (COM7)
COM1 - 通信端口 (COM1)
I see from the PySerial Documentationthat the way to open a COM Port is as below:
我从PySerial 文档中看到打开 COM 端口的方法如下:
import serial
导入序列
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
I am running on Windowsand I get an error for the following line:
我在Windows 上运行,出现以下行错误:
ser = serial.Serial('/dev/ttyUSB0')
ser = serial.Serial('/dev/ttyUSB0')
This is because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?
这是因为 '/dev/ttyUSB0' 在 Windows 中没有意义。我可以在 Windows 中做什么?
采纳答案by pointerless
Thiscould be what you want. I'll have a look at the docs on writing. In windows use COM1 and COM2 etc without /dev/tty/ as that is for unix based systems. To read just use s.read() which waits for data, to write use s.write().
这可能就是你想要的。我会看看关于写作的文档。在 Windows 中使用 COM1 和 COM2 等,没有 /dev/tty/ ,因为这是基于 unix 的系统。读取使用 s.read() 等待数据,写入使用 s.write()。
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
you may need to decode in to get integer values if thats whats being sent.
如果发送的是什么,您可能需要解码以获取整数值。