我有以下代码,我需要一次读取多个传感器。我已经设置了线程和多处理,以为我完成此任务。当线程和mutlipRocessing代码不在主类之外时,它可以正常工作,但是类无法使用其重试的数据。当我将MutlithReading Code Insdie放置时,我会遇到EOFError: Ran out of input
错误。
这是代码:
import os
import multiprocessing
from multiprocessing import Process, Pool
import threading
import queue
import tkinter as tk
from tkinter import *
from tkinter import ttk
import time
import minimalmodbus
import serial
minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
THREAD_LOCK = threading.Lock()
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.first_gas_labelframe = LabelFrame(self, text="Gas 1", width=100)
self.first_gas_labelframe.grid(row=0, column=0)
self.value_label = Label(self.first_gas_labelframe, text="Value")
self.value_label.grid(row=0, column=0)
self.unit_label = Label(self.first_gas_labelframe, text="Unit")
self.unit_label.grid(row=1, column=0)
self.temp_label = Label(self.first_gas_labelframe, text="Temp")
self.temp_label.grid(row=2, column=0)
self.temp_label6 = Label(self.first_gas_labelframe6, text="Temp")
self.temp_label6.grid(row=2, column=0)
self.timer_button = tk.Button(self, text='Start', command=self.start_run)
self.timer_button.grid(row=2, column=0)
def start_run(self):
self.all_thread()
def all_thread(self):
thread = threading.Thread(target=self.all_process)
thread.start()
def all_process(self):
all_ports = port_num()
gas = minimalmodbus.Instrument("COM3", 1)
gas.serial.baudrate = 9600
gas.serial.bytesize = 8
gas.serial.parity = serial.PARITY_NONE
gas.serial.stopbits = 1
gas.serial.timeout = 0.25
gas.mode = minimalmodbus.MODE_RTU
gas_list = [gas]
processes = []
while len(gas_list) > 0:
val = 1
with THREAD_LOCK:
for sen in gas_list:
proc = Process(target=self.main_reader, args=(sen, val))
processes.append(proc)
proc.start()
val += 1
for sen in processes:
sen.join()
time.sleep(1)
def main_reader(sen, val):
try:
read = sen.read_registers(0,42)
except OSError:
read = "Communication Error"
except ValueError:
read = "RTU Error"
print(read)
if __name__ == '__main__':
root = tk.Tk()
root.geometry("1000x600")
app = Application()
app.mainloop()
通过一些调试,问题发生在proc.start()
,但proc
具有数据。这些列表也有数据,这就是为什么我感到困惑为什么它用完输入。注意:在我的代码中,gas_list
您不能使用这样的多处理(嗯,您可以,但是结果将是无法预测的( - 当您创建新过程时,从列表中创建新的minimalmodbus.Instrument
对象时,不会将其传递给参考,但作为一个全新的对象。python本质上会在start()
a multiprocess.Process
实例中运行一个全新的Python解释器实例,并且由于不同的过程获得了不同的堆栈,因此他们无法共享内部内存创建一个幻想,即两个过程(父母和孩子(都有相同的数据。
,您可以自己观察它,如果您可以致电self.main_reader(pickle.loads(pickle.dumps(sen)), val)
,而不是创建新的multiprocessing.Process
(val
也会被腌制,但作为通用,它在这里并不重要(。
Application.main_reader()
方法也发生了同样的过程(尽管定义了奇怪( - 设置它的方式是,您的整个Application
实例实际上在子过程中重新创建,以便Python可以调用其main_reader()
方法。
您可以做的是传递所需的参数以将原始对象重新创建到子过程函数,然后在函数启动时创建对象。例如,如果将Application.all_process()
方法修改为:
def all_process(self):
gas = {"__init__": ("COM3", 1)
"serial": {
"baudrate": 9600,
"bytesize": 8,
"parity": serial.PARITY_NONE,
"stopbits": 1,
"timeout": 0.25
},
"mode": minimalmodbus.MODE_RTU}
gas_list = [gas]
processes = []
while len(gas_list) > 0:
val = 1
for sen in gas_list:
# we'll be calling the main_reader function outside of the Application instead
proc = multiprocessing.Process(target=main_reader, args=(sen, val))
processes.append(proc)
proc.start()
val += 1
for sen in processes:
sen.join()
time.sleep(1)
# you do plan to exit this loop, right?
,然后将您的main_reader()
函数定义在Application
类外部的函数为:
def main_reader(data, val): # notice it's outside of the Application scope
sen = minimalmodbus.Instrument(*data["__init__"]) # initialize Instrument
for k, v in data["serial"].items(): # apply the serial settings
setattr(sen.serial, k, v)
sen.mode = data["mode"] # set the mode
try:
read = sen.read_registers(0, 42)
except OSError:
read = "Communication Error"
except ValueError:
read = "RTU Error"
print(read)
它应该停止丢弃错误。另外,您已经在原始代码中使用了threading.Lock
-我不知道您正在尝试实现什么目标,但是它肯定不会做您认为的事情。