Python pySerial write() 不会接受我的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22275079/
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
pySerial write() won't take my string
提问by Garvin
Using Python 3.3 and pySerial for serial communications.
使用 Python 3.3 和 pySerial 进行串行通信。
I'm trying to write a command to my COM PORT but the write method won't take my string. (Most of the code is from here Full examples of using pySerial package
我正在尝试向我的 COM 端口写入命令,但 write 方法不会接受我的字符串。(大部分代码来自这里使用 pySerial 包的完整示例
What's going on?
这是怎么回事?
import time
import serial
ser = serial.Serial(
port='\\.\COM4',
baudrate=115200,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write("%01#RDD0010000107**\r")
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(40)
if out != '':
print(">>" + out)
ser.close()
Error is at ser.write("%01#RDD0010000107**\r") where it gets Traceback is like this data = to_bytes(data) b.append(item) TypeError: an integer is required.
错误是在 ser.write("%01#RDD0010000107**\r") 那里它得到回溯就像这个 data = to_bytes(data) b.append(item) TypeError: an integer is required。
采纳答案by Garvin
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to
事实证明,需要将字符串转换为字节数组,为此我将代码编辑为
ser.write("%01#RDD0010000107**\r".encode())
This solved the problem
这解决了问题
回答by user3577539
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
尝试写入时,我收到了相同的“TypeError: an integer is required”错误消息。谢谢, .encode() 为我解决了它。我在运行 32 位 Windows XP Pro 的 Dell D530 上运行 python 3.4。
I'm omitting the com port settings here:
我在这里省略了 com 端口设置:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
回答by Murphy Meng
You have found the root cause. Alternately do like this:
你已经找到了根本原因。或者这样做:
ser.write(bytes(b'your_commands'))

