2016-06-16 222 views
0

我想了解为什么在导入后,实例化的模块变量在被修改后不会重置。我一直在使用minimalmodbus,如果默认值与连接的设备不匹配,我试图重置波特率。设置我自己的默认值,我不能重新初始化minimalmodbus来更改波特率。例如:重置导入的Python模块变量

import minimalmodbus 
minimalmodbus.BAUDRATE=9600 
comm=minimalmodbus.Instrument('COM4',1) #baud rate set to 9600 here for comm 
minimalmodbus.BAUDRATE=19200 
comm=minimalmodbus.Instrument('COM4',1) #attempting to change baud rate 
print comm #displays all information, and showing that baudrate=9600, not 19200 

我有这个问题使用了其他几个模块,我真的很想明白为什么会发生这种情况。

回答

1

您使用给定的串行端口,minimalmodbuscreates a serial.Serial instance using the current value of BAUDRATE and saves it第一次:

def __init__(self, port, slaveaddress, mode=MODE_RTU): 
    if port not in _SERIALPORTS or not _SERIALPORTS[port]: 
     self.serial = _SERIALPORTS[port] = serial.Serial(port=port, baudrate=BAUDRATE, parity=PARITY, bytesize=BYTESIZE, stopbits=STOPBITS, timeout=TIMEOUT) 
    else: 
     self.serial = _SERIALPORTS[port] 
     if self.serial.port is None: 
      self.serial.open() 
    ... 

即使BAUDRATE变化后,以后尝试使用串行端口将使用旧serial.SERIAL实例与旧的波特率。

我不知道Modbus协议是什么样的,或者你应该如何使用这个模块,所以我不能告诉你你应该怎么做你想做的事情,或者它是一个好主意。无论如何,现在你知道发生了什么。

+0

我完全忘记了MinimalModbus和Serial之间的关系。谢谢! – atf