[英]Python: setting variables that belong to the namespace of an imported module
[英]Resetting imported Python module variables
我試圖理解為什么實例化的模塊變量在導入后被修改一次后就不會重置。 我一直在使用minimalmodbus
,並且如果默認值與所連接設備的波特率不匹配,則嘗試重置波特率。 設置自己的默認值后,我無法重新初始化minimalmodbus
以更改波特率。 例如:
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
我使用其他幾個模塊遇到了這個問題,我真的很想了解為什么會這樣。
第一次使用給定的串行端口時, minimalmodbus
使用當前的BAUDRATE
值創建一個serial.Serial
實例並將其保存 :
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協議是什么樣的,也不知道如何使用此模塊,因此我無法告訴您應該如何做您要嘗試做的事情,或者這是否是個好主意。 無論如何,現在您知道發生了什么事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.