使用pySerial关闭和重新打开com端口会导致FileNotFoundError

问题描述

我对看似简单的一段代码有疑问。我正在使用bus pirate来控制微控制器。我正在使用python与该海盗进行通信。代码如下:

from serial import Serial

class BusPirate(Serial):
    '''
    Bus pirate for all hardware
    '''
    def __init__(self,com_port):
        super().__init__(com_port,115200,timeout=0.25,xonxoff=True)
        self.close()
    
    
    def initialize(self):
        buspirate_init_commands = [
         '#',# reset bus pirate (slow,maybe not needed)
         'm',# change mode (goal is to get away from HiZ)
         '5',# mode 5 is SPI
         '4',# set speed to 125KHz
         '1',# set speed to 30KHz
         '1',# set clock idle state 'low'
         '2',# set output clock edge active to idle
         '1',# set input sample phase to 'middle'
         'W',# turn power supply to ON. Lowercase w for OFF.
         '[110,4,0]']  # init span to +-2V
        for cmd in buspirate_init_commands:
            self.send(cmd,keep_open=True)
        self.close()
        
    def send(self,cmd,keep_open=True,verbose=False):
        """send the command and listen to the response."""
        if not self.is_open:
            self.open()
        self.write(str(cmd+'\n').encode('ascii')) # send our command
        for line in self.readlines(): # while there's a response
            if verbose==True:
                print(line.decode('utf-8').strip()) # show it
        if not keep_open:
            self.close()

device = BusPirate('COM6')
device.initialize()

设备的实例工作正常,但是一旦运行device.initialize(),我就会收到FileNotFoundError,抱怨它找不到'COM6'。有什么明显的地方我做错了吗?

我之所以要尽快关闭com端口,是因为另一个程序(如果您有兴趣,请使用Quartus FPGA编程器)会在打开任何com端口时抱怨。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)