多处理功能不写入文件或打印

Multiprocessing function not writing to file or printing

我正在研究 Raspberry Pi (3 B+) 制作数据收集设备,我正在 试图生成一个进程来记录传入的数据并将其写入文件。我有一个写作功能,当我直接调用它时可以正常工作。

然而,当我使用多进程方法调用它时,似乎什么也没有发生。我可以在 Linux 的任务监视器中看到该进程实际上已生成但没有写入任何文件,并且当我尝试将标志传递给它以关闭它时它不起作用,这意味着我最终终止了这个过程,似乎什么都没发生。

我已经从各个方面解决了这个问题,看不出我做错了什么;其他人呢?如果相关,这些是父函数 class 中的函数,其中一个函数旨在将另一个函数作为线程生成。

我使用的代码:

from datetime import datetime, timedelta
import csv
from drivers.IMU_SEN0 import IMU_SEN0
import multiprocessing, os

class IMU_data_logger:
    _output_filename = ''
    _csv_headers = []
    _accelerometer_headers = ['Accelerometer X','Accelerometer    Y','Accelerometer Z']
    _gyroscope_headers = ['Gyroscope X','Gyroscope Y','Gyroscope Z']
    _magnetometer_headers = ['Bearing']
    _log_accelerometer = False
    _log_gyroscope= False
    _log_magnetometer = False
    IMU = None
    _writer=[]
    _run_underway = False
    _process=[]
    _stop_value = 0

def __init__(self,output_filename='/home/pi/blah.csv',log_accelerometer = True,log_gyroscope= True,log_magnetometer = True):
    """data logging device
    NOTE! Multiple instances of this class should not use the same IMU devices simultaneously!"""        
    self._output_filename = output_filename
    self._log_accelerometer = log_accelerometer
    self._log_gyroscope = log_gyroscope
    self._log_magnetometer = log_magnetometer

def __del__(self):
    # TODO Update this
    if self._run_underway: # If there's still a run underway, end it first
        self.end_recording()

def _set_up(self):        
    self.IMU = IMU_SEN0(self._log_accelerometer,self._log_gyroscope,self._log_magnetometer)
    self._set_up_headers()

def _set_up_headers(self):
    """Set up the headers of the CSV file based on the header substrings at top and the input flags on what will be measured"""
    self._csv_headers = []
    if self._log_accelerometer is not None:
        self._csv_headers+= self._accelerometer_headers
    if self._log_gyroscope is not None:
        self._csv_headers+= self._gyroscope_headers
    if self._log_magnetometer is not None:
        self._csv_headers+= self._magnetometer_headers


def _record_data(self,frequency,stop_value):
    self._set_up() #Run setup in thread

    """Record data function, which takes a recording frequency, in herz, as an input"""
    previous_read_time=datetime.now()-timedelta(1,0,0)
    self._run_underway = True # Note that a run is now going
    Period = 1/frequency # Period, in seconds, of a recording based on the input frequency
    print("Writing output data to",self._output_filename)

    with open(self._output_filename,'w',newline='') as outcsv:
        self._writer = csv.writer(outcsv)
        self._writer.writerow(self._csv_headers) # Write headers to file

        while stop_value.value==0: # While a run continues
            if datetime.now()-previous_read_time>=timedelta(0,1,0): # If we've waited a period, collect the data; otherwise keep looping
                print("run underway value",self._run_underway)
            if datetime.now()-previous_read_time>=timedelta(0,Period,0): # If we've waited a period, collect the data; otherwise keep looping
                previous_read_time = datetime.now() # Update previous readtime
                next_row = []
                if self._log_accelerometer:
                    # Get values in m/s^2
                    axes = self.IMU.read_accelerometer_values()
                    next_row += [axes['x'],axes['y'],axes['z']]

                if self._log_gyroscope:
                    # Read gyro values
                    gyro = self.IMU.read_gyroscope_values()
                    next_row += [gyro['x'],gyro['y'],gyro['z']]

                if self._log_magnetometer:
                    # Read magnetometer value
                    b= self.IMU.read_magnetometer_bearing()
                    next_row += b

                self._writer.writerow(next_row)

        # Close the csv when done
        outcsv.close()

def start_recording(self,frequency_in_hz):        
    # Create recording process
    self._stop_value = multiprocessing.Value('i',0)
    self._process = multiprocessing.Process(target=self._record_data,args=(frequency_in_hz,self._stop_value))

    # Start recording process
    self._process.start()
    print(datetime.now().strftime("%H:%M:%S.%f"),"Data logging process spawned")
    print("Logging Accelerometer:",self._log_accelerometer)
    print("Logging Gyroscope:",self._log_gyroscope)
    print("Logging Magnetometer:",self._log_magnetometer)     
    print("ID of data logging process: {}".format(self._process.pid))

def end_recording(self,terminate_wait = 2):
    """Function to end the recording multithread that's been spawned.
    Args: terminate_wait: This is the time, in seconds, to wait after attempting to shut down the process before terminating it."""
    # Get process id
    id = self._process.pid

    # Set stop event for process
    self._stop_value.value = 1

    self._process.join(terminate_wait) # Wait two seconds for the process to terminate
    if self._process.is_alive(): # If it's still alive after waiting
        self._process.terminate()
        print(datetime.now().strftime("%H:%M:%S.%f"),"Process",id,"needed to be terminated.")
    else:
        print(datetime.now().strftime("%H:%M:%S.%f"),"Process",id,"successfully ended itself.")

============================================= =======================

答案:对于跟进这里的任何人,事实证明问题是我使用了 VS 代码调试器,它显然不适用于多处理并且以某种方式阻止了成功产生的过程。非常感谢下面的 Tomasz Swider 帮助我解决问题并最终发现我的愚蠢。非常感谢您的帮助!!

我看不出你的代码有什么问题:

第一件事 stop_value == 0 将不起作用,因为 multiprocess.Value('i', 0) != 0,将该行更改为

while stop_value.value == 0

其次,你从不更新 previous_read_time 所以它会尽可能快地写入读数,你会 运行 很快用完磁盘

第三,尝试使用 time.sleep() 你正在做的事情叫做忙循环,这很糟糕,它在不必要地浪费 CPU 个周期。

四,以 self._stop_value = 1 结尾可能行不通必须有其他方法来设置该值可能 self._stop_value.value = 1.

这里是基于您提供的代码的示例代码,运行良好:

import csv
import multiprocessing
import time
from datetime import datetime, timedelta
from random import randint


class IMU(object):

    @staticmethod
    def read_accelerometer_values():
        return dict(x=randint(0, 100), y=randint(0, 100), z=randint(0, 10))


class Foo(object):

    def __init__(self, output_filename):
        self._output_filename = output_filename
        self._csv_headers = ['xxxx','y','z']
        self._log_accelerometer = True
        self.IMU = IMU()

    def _record_data(self, frequency, stop_value):
        #self._set_up()  # Run setup functions for the data collection device and store it in the self.IMU variable

        """Record data function, which takes a recording frequency, in herz, as an input"""
        previous_read_time = datetime.now() - timedelta(1, 0, 0)
        self._run_underway = True  # Note that a run is now going
        Period = 1 / frequency  # Period, in seconds, of a recording based on the input frequency
        print("Writing output data to", self._output_filename)

        with open(self._output_filename, 'w', newline='') as outcsv:
            self._writer = csv.writer(outcsv)
            self._writer.writerow(self._csv_headers)  # Write headers to file

            while stop_value.value == 0:  # While a run continues
                if datetime.now() - previous_read_time >= timedelta(0, 1,
                                                                    0):  # If we've waited a period, collect the data; otherwise keep looping
                    print("run underway value", self._run_underway)
                if datetime.now() - previous_read_time >= timedelta(0, Period,
                                                                    0):  # If we've waited a period, collect the data; otherwise keep looping
                    next_row = []
                    if self._log_accelerometer:
                        # Get values in m/s^2
                        axes = self.IMU.read_accelerometer_values()
                        next_row += [axes['x'], axes['y'], axes['z']]

                    previous_read_time = datetime.now()
                    self._writer.writerow(next_row)

            # Close the csv when done
            outcsv.close()

    def start_recording(self, frequency_in_hz):
        # Create recording process
        self._stop_value = multiprocessing.Value('i', 0)
        self._process = multiprocessing.Process(target=self._record_data, args=(frequency_in_hz, self._stop_value))

        # Start recording process
        self._process.start()
        print(datetime.now().strftime("%H:%M:%S.%f"), "Data logging process spawned")
        print("ID of data logging process: {}".format(self._process.pid))

    def end_recording(self, terminate_wait=2):
        """Function to end the recording multithread that's been spawned.
        Args: terminate_wait: This is the time, in seconds, to wait after attempting to shut down the process before terminating it."""
        # Get process id
        id = self._process.pid

        # Set stop event for process
        self._stop_value.value = 1

        self._process.join(terminate_wait)  # Wait two seconds for the process to terminate
        if self._process.is_alive():  # If it's still alive after waiting
            self._process.terminate()
            print(datetime.now().strftime("%H:%M:%S.%f"), "Process", id, "needed to be terminated.")
        else:
            print(datetime.now().strftime("%H:%M:%S.%f"), "Process", id, "successfully ended itself.")


if __name__ == '__main__':
    foo = Foo('/tmp/foometer.csv')
    foo.start_recording(20)
    time.sleep(5)
    print('Ending recording')
    foo.end_recording()