EOFError:跑出类内的输入

发布于 2021-01-29 16:07:10

我有以下代码,需要一次读取多个传感器。我已经设置了线程和多处理功能来为我完成此任务。当线程和多处理代码不在主类之外时,它可以正常工作,但该类无法使用其检索的数据。当我将多线程代码插入类中时,我遇到了一个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

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您不能使用这样的多重处理(可以,但是结果将是不可预测的)-当您创建一个新进程时minimalmodbus.Instrument,列表中的对象不会作为引用传递,而是作为一个完整的新对象传递。无论何时您start()使用multiprocess.Process实例,Python实质上都会运行一个全新的Python解释器实例,并且由于不同的进程获得不同的堆栈,因此它们无法共享内部内存,因此Python实际上会腌制所传递的参数,将其发送给Process,然后在其上进行点刺,从而创建幻想两个进程(父和子)具有相同的数据。

    您可以自己观察它,而不是创建一个新的multiprocessing.Process调用self.main_reader(pickle.loads(pickle.dumps(sen)), val)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在原始代码中使用过-我不知道您尝试使用它实现什么,但是最肯定的是,它并没有实现您认为的目标。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看