Python 3.4和pySerial2.7“写入串口?”

时间:2014-07-06 01:34:55

标签: python-3.x pyserial

我对Python很新,但我发现它非常有用。我有一个简单的应用程序从COM34读取数据并将其存储在一个文件中,这很好用!!我现在正在尝试向同一个COM34端口写一个简单的命令。当我按照许多区域中显示的示例时,我收到以下错误......?

追踪(最近一次呼叫最后一次):

File "C:/Projects_All/EmbeddedMasters/Firmware/Python/my_Serial.py", line 26, in <module>
port.write("hello")
File "C:\Python34\lib\site-packages\serial\serialwin32.py", line 283, in write
data = to_bytes(data)
File "C:\Python34\lib\site-packages\serial\serialutil.py", line 76, in to_bytes
b.append(item)  # this one handles int and str for our emulation and ints for Python 3.x
TypeError: an integer is required

这是我的代码,我们将非常感谢任何帮助!!

import serial

addr = 'COM34'
baud = '3000000'
fname = 'my_test.dat'
fmode = 'w'
reps = 100
bufferVal = 256

with serial.Serial(addr,baud) as port, open(fname,fmode, bufferVal) as outf:
    print(port)
    print(outf)
#    header = "Is it writing to file?\n"
#    outf.write(header)
    for i in range(reps):
        x = port.readline()
        s = str(x)
        print(s)
        outf.write(s)
        outf.write('\n')
        outf.flush()
        port.write("hello")

2 个答案:

答案 0 :(得分:1)

试试这个: port.write( “你好” .encode())

答案 1 :(得分:1)

我想7个月后你可能找到了答案, 如果没有我的建议

How to Fix TypeError: an integer is required in python 3.4, pyserial 2.7 virtual serial port

我曾经有同样的问题,但我找到了答案

outf.write(temp1.encode('utf-8'))<------- in your case

当Python分配命令.write IT必须有.endcode()或.encode('utf-8')或('hex')或('ascii')等检查此链接https://docs.python.org/2/library/codecs.html#standard-encodings并且这个一个http://www.tutorialspoint.com/python/string_encode.htm