我有一个串行日志记录实用程序,它处理来自COM端口的日志并将它们发送到DB。我将pyserial ReaderThread与协议工厂结合使用。
class SerialLogging(Process):
def __init__(self, cpath, q):
Process.__init__(self)
self.__queue = q
config = configparser.ConfigParser()
config.optionxform = str
config.read(cpath)
self.__configs = list()
for section in config.sections():
self.__configs.append(dict(config.items(section)))
if len(self.__configs) <= 0:
return 1
self.__serials = list()
for config in self.__configs:
if config['status'] == 'on':
self.__serials.append({'thread': threaded.ReaderThread(serial.Serial(config['port'], baudrate=config['baudrate'], timeout=1), lambda config=config: PrintLines(config['device'])), 'port': config['port'], 'device': config['device'], 'baudrate' : config['baudrate']})
for ser in self.__serials:
try:
ser['thread'].start()
ser['status'] = 'on'
except:
ser['status'] = 'off'
def run(self):
while True:
try:
message = self.__queue.get_nowait()
self.__queue.task_done()
except queue.Empty:
continue
if 'close' in message:
self.__disable(message.split(' ')[1])
self.__queue.put('ok')
elif 'run' in message:
self.__enable(message.split(' ')[1])
self.__queue.put('ok')
elif 'list' in message:
self.__queue.put(self.__list())
return
def __disable(self, port):
for serial in self.__serials:
if serial['port'] == port and serial['status'] == 'on':
serial['thread'].close()
serial['status'] = 'off'
def __enable(self, port):
for ser in self.__serials:
if ser['port'] == port and ser['status'] == 'off':
ser['thread'] = threaded.ReaderThread(serial.Serial(ser['port'], baudrate=ser['baudrate'], timeout=1), lambda ser=ser: PrintLines(ser['device']))
ser['thread'].start()
ser['status'] = 'on'
def __list(self):
return ['%s=%s %s' % (serial['port'], serial['device'], serial['status']) for serial in self.__serials]
SerialLogging类被实例化为一个单独的进程。 问题是ReaderThreads以某种方式从子进程(它们已经启动到父进程)复制,所以当我停止线程时,它只在子进程中停止并继续从父进程记录信息。 关于这个问题的任何建议?真的很感谢你的帮助。
答案 0 :(得分:0)
我在子进程中创建线程,这是错误的。