簡體   English   中英

如何在 Python 中實現和執行具有多個類的線程?

[英]How do I implement and execute threading with multiple classes in Python?

我對 Python 非常陌生(我以前的大部分編程經驗都是在中間 C++ 和 Java 中)並且正在嘗試開發一個腳本來讀取傳感器數據並將其記錄到 a.Z628CB5675FF524F3E719B7AZE 文件。 為此,我為代碼創建了單獨的類——一個將讀取傳感器數據並將 output 讀取到控制台,而另一個則應該獲取該數據並記錄它——並將它們組合成一個包含每個 class 的主腳本. 單獨地,它們工作得很好,但只有 sensorReader class 一起工作。 我試圖讓每個 class 在自己的線程中運行,同時將傳感器數據從第一個 class(sensorReader)傳遞到第二個 class(csvWriter)。 我在下面發布了一些偽代碼,但如果需要,我很樂意用實際源代碼澄清任何問題。

import time
import sensorStuff
import csv
import threading
import datetime


class sensorReader:

    # Initializers for the sensors.
    this.code(initializes the sensors)

    while True:

        try:
            this.code(prints the sensor data to the console)

        this.code(throws exceptions)

        this.code(waits 60 seconds)


class csvWriter:

    this.code(fetches the date and time)

    this.code(writes the headers for the excel sheet once)

    while True: 
        this.code(gets date and time)

        this.code(writes the time and one row of data to excel)

        this.code(writes a message to console then repeats every minute)


r = sensorReader()
t = threading.Thread(target = r, name = "Thread #1")
t.start()
t.join
w = csvWriter()
t = threading.Thread(target = w, name = "Thread #2")
t.start() 

我意識到最后一部分並沒有真正的意義,但我真的在這里超過了我的體重,所以我什至不確定為什么只有第一個 class 有效,而不是第二個有效,更不用說如何為多個類實現線程. 如果有人能指出我正確的方向,我將不勝感激。

謝謝!

編輯

我決定貼出完整的源代碼:

import time
import board
import busio
import adafruit_dps310
import adafruit_dht
import csv
import threading
import datetime
# import random


class sensorReader:

    # Initializers for the sensors.
    i2c = busio.I2C(board.SCL, board.SDA)
    dps310 = adafruit_dps310.DPS310(i2c)
    dhtDevice = adafruit_dht.DHT22(board.D4)

    while True:

        # Print the values to the console.
        try:
            global pres
            pres = dps310.pressure
            print("Pressure = %.2f hPa"%pres)
            global temperature_c
            temperature_c = dhtDevice.temperature
            global temperature_f
            temperature_f = temperature_c * (9 / 5) + 32
            global humidity
            humidity = dhtDevice.humidity
            print("Temp: {:.1f} F / {:.1f} C \nHumidity: {}% "
                .format(temperature_f, temperature_c, humidity))
            print("")

        # Errors happen fairly often with DHT sensors, and will occasionally throw exceptions.
        except RuntimeError as error:
            print("n/a")
            print("")

        # Waits 60 seconds before repeating.
        time.sleep(10)


class csvWriter:

    # Fetches the date and time for future file naming and data logging operations.
    starttime=time.time()
    x = datetime.datetime.now()

    # Writes the header for the .csv file once.
    with open('Weather Log %s.csv' % x, 'w', newline='') as f:
        fieldnames = ['Time', 'Temperature (F)', 'Humidity (%)', 'Pressure (hPa)']
        thewriter = csv.DictWriter(f, fieldnames=fieldnames)
        thewriter.writeheader()

    # Fetches the date and time.
    while True: 
        from datetime import datetime
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        # Writes incoming data to the .csv file.
        with open('Weather Log %s.csv', 'a', newline='') as f: 
            fieldnames = ['TIME', 'TEMP', 'HUMI', 'PRES'] 
            thewriter = csv.DictWriter(f, fieldnames=fieldnames)
            thewriter.writerow({'TIME' : current_time, 'TEMP' : temperature_f, 'HUMI' : humidity, 'PRES' : pres})

        # Writes a message confirming the data's entry into the log, then sets a 60 second repeat cycle.
        print("New entry added.")
        time.sleep(10.0 - ((time.time() - starttime) % 10.0)) # Repeat every ten seconds.

r = sensorReader()
t = threading.Thread(target = r, name = "Thread #1")
t.start()
t.join
w = csvWriter()
t = threading.Thread(target = w, name = "Thread #2")
t.start()

這樣的結構會更好。 如果將第一個循環放在 function 中,則可以延遲其評估,直到准備好啟動線程。 但是在 class 主體中,它會立即運行,而您永遠不會到達第二個定義。

def sensor_reader():
    # Initializers for the sensors.
    this.code(initializes the sensors)
    while True:
        try:
            this.code(prints the sensor data to the console)
        except:
            print()
        this.code(waits 60 seconds)


threading.Thread(target=sensor_reader, name="Thread #1", daemon=True).start()

this.code(fetches the date and time)
this.code(writes the headers for the excel sheet once)
while True: 
    this.code(gets date and time)
    this.code(writes the time and one row of data to excel)
    this.code(writes a message to console then repeats every minute)

我把它做成了一個守護進程,所以當你終止程序時它會停止。 另請注意,我們只需要創建一個線程,因為我們已經有了主線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM