我正在尝试从 PySerial 文档运行此示例程序以打开串行端口。资料来源:http://pyserial.sourceforge.net/shortintro.html 我尝试在 python 2.7 和 3.4 版本中运行代码,但仍然遇到相同的错误。
>>> import serial
>>> ser = serial.Serial(0) # open first serial port
>>> print ser.name # check which port was really used
>>> ser.write("hello") # write a string
>>> ser.close() # close port
运行第二行代码后出现以下错误:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
ser = serial.Serial(0)
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
SerialException: could not open port 'COM1': WindowsError(2, 'The system cannot find the file specified.')
听起来 COM1 不可用(它不存在或已被使用)。 我制作了这个小脚本来列出可用的 COM 端口。
import serial
ser=serial.Serial()
for ns in xrange(101):
try:
ser.port=ns
ser.open()
print "COM"+str(ns+1)+" available"
ser.close()
except serial.SerialException:
print "COM"+str(ns+1)+" NOT available"
记住COM端口号是你传递给serial的数字+1(serial.Serial(0)打开COM1,serial.Serial(1)打开COM2等)