python串口代码在windows中工作,但在linux中不工作

Posted

技术标签:

【中文标题】python串口代码在windows中工作,但在linux中不工作【英文标题】:python serial port code is working in windows but not in linux 【发布时间】:2013-12-05 23:02:56 【问题描述】:

我编写了一些在 windows 中运行良好但在 linux (ubuntu 12.04) 中运行良好的 python 代码。 我收到这条消息:

File "mygui.py", line 50, in sendPacket
returnpacket = str(length) + str(com3.read(ord(length)-1))
TypeError: ord() expected a character, but string of length 0 found

这是我的代码:

import serial
import crc16pure
import time

def main():
#works for 115200, 250000, 500000, 1000000
com3 = serial.Serial('/dev/ttyUSB0',baudrate=1000000,dsrdtr=False)
com3.timeout = 10
time.sleep(5) #MUST wait this long before writing, otherwise the serial
#p = '"aaaaaaaaaaaaaaaa","  ","iget",null'
p = '"SensorNodeUUID":"aaaaaaaaaaaaaaaa","SlaveUUID":"  ","Command":"iget","Args":null'
#discard first byte
com3.read()
timesum = 0
lstart = time.clock()

for i in range(3):
#print("writing packet")
start = time.clock()
#print(preparepacket(p))
com3.write(preparepacket(p))

length = com3.read()


returnpacket = str(length) + str(com3.read(ord(length)-1))
print(returnpacket)
com3.close()

【问题讨论】:

【参考方案1】:

我已经很多年没有写过连续剧了,从那以后我就写过 bufsock ......你可以试试 bufsock 看看它是否对你的情况有帮助: http://stromberg.dnsalias.org/~dstromberg/bufsock.html

它会处理诸如等到一个字节准备好,然后再放弃读取之类的事情。我在 Cygwin 上使用过,但从未使用过原生 Windows Python。但众所周知,它可以在 *ix 上运行 CPython 2.x、CPython 3.x、Jython 和 Pypy。

不要让名字欺骗了你 - 我写它是为了缓冲套接字,但它也适用于文件句柄。

【讨论】:

以上是关于python串口代码在windows中工作,但在linux中不工作的主要内容,如果未能解决你的问题,请参考以下文章

Telnet Java 代码在 Windows 中工作,但在 Unix 中不工作

Python代码在shell中工作正常,但在文件中调用时不能

CreateFile() 在 Windows XP 中工作,但在 Windows 7 中失败,返回句柄无效

Powerpoint Interop 在 Windows 服务中失败,但在 Windows 窗体应用程序中工作正常

“GET”请求在 Python 中工作,但在机器人框架中不起作用

Jquery 表单提交不能在 chrome 中工作,但在 Firefox 中工作