2016-06-16 142 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