[英]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.