Python / Pyserial:从端口

时间:2016-08-05 13:23:56

标签: python pyserial virtual-serial-port

我刚刚开始使用pyserial,因为我最终需要读取/保存来自特定端口的信息。使用下面的代码我只打印使用的端口,然后尝试编写然后读入一些文本(" hello")。端口打印正常,但我的字符串输出结果为5.知道为什么会这样吗?

import serial
import sys
from time import sleep

try:
  ser = serial.Serial('\\.\COM8', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)

except:
    sys.exit("Error connecting device")

print ser.portstr

x = ser.write("hello")
print x

ser.close()  

输出:

>>> 
\.\COM8
5
>>> 

另外,有一种简单的方法让我模仿来自端口的文本信息流,以便我可以测试读取/保存传入的信息吗?

我正在使用Python 2.7和'虚拟串口驱动程序8.0' [Eltima VSPD]模拟一个端口来测试这些东西。

谢谢, 史蒂夫

2 个答案:

答案 0 :(得分:1)

你可以这样做来测试它。首先在管理端口中创建一对端口

第一个端口:COM199 第二个港口:COM188

点击添加对

在一个控制台/脚本上执行以下步骤:

>>> import serial
>>> ser = serial.Serial('COM196', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.S
BITS_ONE, bytesize=serial.EIGHTBITS)
>>> print ser.portstr
COM196
>>> x = ser.read(5) # It will be waiting till it receives data
>>> print x
hello

在其他控制台上,执行以下步骤:

>>> import serial
>>> s = serial.Serial('COM188')
>>> s.write("hello")
5L

你可以通过为每个端口创建python程序来以这种方式(或)进行测试

答案 1 :(得分:0)

x = ser.write("hello")
print x

你写这个是发送的。这不是收到的信息。可能它写了你已经发出的字符串的长度。 首先,您需要有一个客户端脚本,它将响应您的已发送信息。

你必须使用这样的东西。

...     x = ser.read()          # read one byte
...     s = ser.read(10)        # read up to ten bytes (timeout)
...     line = ser.readline()   # read a '\n' terminated line
相关问题