亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

多處理功能不寫入文件或打印

多處理功能不寫入文件或打印

江戶川亂折騰 2021-09-28 21:07:41
我正在使用 Raspberry Pi (3 B+) 制作數據收集設備,我正在嘗試生成一個進程來記錄傳入的數據并將其寫入文件。我有一個寫作函數,當我直接調用它時可以正常工作。然而,當我使用多進程方法調用它時,似乎什么也沒發生。我可以在 Linux 的任務監視器中看到該進程確實被生成但沒有文件被寫入,并且當我嘗試將標志傳遞給它以關閉它時它不起作用,這意味著我最終終止了該進程而什么也沒有似乎已經發生了。我已經從各個方面解決了這個問題,但看不出我做錯了什么;還有其他人嗎?如果相關,這些是父類中的函數,其中一個函數旨在生成另一個作為線程的函數。我正在使用的代碼:from datetime import datetime, timedeltaimport csvfrom drivers.IMU_SEN0 import IMU_SEN0import multiprocessing, osclass 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 = 0def __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_magnetometerdef __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()答案:對于在這里跟進的任何人,事實證明問題在于我使用了 VS Code 調試器,該調試器顯然不適用于多處理,并且以某種方式阻止了生成的進程的成功。
查看完整描述

1 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

我可以在您的代碼中看到一些錯誤:


首先 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()



查看完整回答
反對 回復 2021-09-28
  • 1 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號