我在使用Python端口的pyserial和Python 3.3中看到了stackoverflow中的简单代码,但我无法在我的新安装的pyserial 2.7 [在Windows 7,64位,带有3个USB端口]上工作。 pyserial的安装顺利进行,我可以毫无错误地导入,并且在Pyscripter IDE中识别出方法,这增强了对良好安装的信心,但是:
代码被剥离到产生必需品的错误是:
import serial
def main():
ser = serial.Serial(port='COM2')
ser.close()
if __name__ == '__main__':
main
从这里我收到一个错误“SerialException:无法打开端口'COM2'的对话框:FileNotFoundError(2,'系统找不到指定的文件。',无,2)”
Traceback声明:
*** Remote Interpreter Reinitialized ***
>>>
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "C:\Python33\Lib\site-packages\scanport2.py", line 19, in <module>
main()
File "C:\Python33\Lib\site-packages\scanport2.py", line 15, in main
ser = serial.Serial(port='COM2')
File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python33\Lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM2': FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)
导入模块中引发SerialException的代码段是:
# the "\\.\COMx" format is required for devices other than COM1-COM8
# not all versions of windows seem to support this properly
# so that the first few ports are used with the DOS device name
port = self.portstr
try:
if port.upper().startswith('COM') and int(port[3:]) > 8:
port = '\\\\.\\' + port
except ValueError:
# for like COMnotanumber
pass
self.hComPort = win32.CreateFile(port,
win32.GENERIC_READ | win32.GENERIC_WRITE,
0, # exclusive access
None, # no security
win32.OPEN_EXISTING,
win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
0)
if self.hComPort == win32.INVALID_HANDLE_VALUE:
self.hComPort = None # 'cause __del__ is called anyway
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
我确实有一个连接到COM2的活动设备,如Windows设备管理器中所标识的那样。我也试过扫描所有端口,但代码在第一次使用serial.Serial
时停止看来win32会发生什么事情?
我是Python与硬件接口的新手。
答案 0 :(得分:0)
我会尝试以下方法:
GLOBAL??
文件夹;你应该在那里看到COM2作为一个符合更多驱动程序的符号链接。\\.\USBSER000
代替COM2
,但要记得正确地逃避这些反斜杠。答案 1 :(得分:0)
看起来pyserial download page只包含32位python的链接?这个unofficial page似乎有64位安装的链接,但是要从未知来源安装谨慎。
此答案还建议使用pip
:https://stackoverflow.com/a/8491164/66349