簡體   English   中英

使用多處理在 While True 循環中使用 PyMongo 上傳

[英]Uploading with PyMongo in a While True loop using Multiprocessing

我有一個腳本,可以通過開發板的串口讀取數據。 我想讓這個腳本在每個循環結束時將數據上傳到 MongoDB 集合,但我不希望循環因為上傳而阻塞。 當我嘗試使用多處理庫這樣做時,循環只上傳一個空白文檔。

client = MongoClient()
db = client['CompostMonitor-1']

def upload_to_database(data):
    # Connect to the collection where the data will be stored
    collection = db.RedBoard

    # Insert the data into the collection
    collection.insert_one(data)


port = '/dev/ttyUSB0'
filename = '~/TestData'
containernumber = 1
baud_rate = 9600
RBSerial = serial.Serial(port, baud_rate, timeout=1)
directoryBase = "{}/{}/Bucket {}/RB".format(filename, time.strftime("%m-%d-%Y"), containernumber)
pathlib.Path(directoryBase).mkdir(parents=True, exist_ok=True)
logFileRB = '{}/RB_Bucket_{}_{}_{}_log.bin'.format(directoryBase, containernumber, time.strftime("%m-%d-%Y"),
                                                   time.strftime("%H;%M;%S"))
csvRB = '{}/RB_Bucket_{}_{}_{}.csv'.format(directoryBase, containernumber, time.strftime("%m-%d-%Y"),
                                           time.strftime("%H;%M;%S"))

startup = True

count = 0
bytearray = []
RB_DataList = []
RB_DataDict = {}

header = ['Date/Time',
          'SGP TVOC (ppb)',
          'BME Humidity (%)',
          'BME Pressure (Pa)',
          'BME Temp (Deg C)']

startTime = time.time()

p = multiprocessing.Process(target=upload_to_database, args=(RB_DataDict,))

while 1:
    RB_DataDict = {'_id': ''}
    RB_inbyte = RBSerial.read(size=1)
    with open(logFileRB, 'ab') as l:
        l.write(RB_inbyte)
    bytearray.append(RB_inbyte)
    if RB_inbyte == b'\n':
        bytearray.pop()
        with open(csvRB, 'a', newline = '') as table:
            writer = csv.writer(table)
            if count == 0:
                writer.writerow(header)
            RB_DataSplit = ''.join(str(bytearray)).replace(" ", "").replace('b', '').replace("'", '').replace(",", '').\
                replace('[', '').replace(']', '').split(';')
            RB_DataList.append(time.strftime("%m-%d-%Y %H:%M:%S"))
            for i in range(len(RB_DataSplit)):
                RB_DataList.append(RB_DataSplit[i])
            print(RB_DataList)
            writer.writerow(RB_DataList)
            RB_DataDict = {'Date_Time': RB_DataList[0], 'TVOC Con': RB_DataList[1], 'BME Humidity': RB_DataList[2],
                           'BME Pressure': RB_DataList[3], 'BME Temp': RB_DataList[4]}
            print(RB_DataDict)
            RB_DataList = []
            # upload_to_database(RB_DataDict)
            if startup:
                p.start()
                startup = False

        bytearray = []

但是,如果我只是像注釋行中那樣調用upload_to_database(RB_DataDict) ,它就會按預期工作。 認為啟動該過程會不斷將 RB_DataDict 上傳到我的 Mongo 數據庫,但它似乎只運行一次然后停止。

我還沒有找到任何嘗試在無限循環中使用多處理的代碼示例,因此很難將我的代碼與有效代碼進行比較。 我如何更改此代碼,以便每次填充字典時使用多處理對象上傳 RB_DataDict?

我找到了解決問題的方法。 我真的不明白為什么它如此有效,但確實如此:

if __name__ == '__main__':
    if startup:
        p.start()
        startup = False
        print('Startup == False')

    else:
        # Close the process instance and start a new one!
        p.close()
        p = multiprocessing.Process(target= upload_to_database, args = (RB_DataDict,))
        p.start()
        print('should have uploaded something here')

只需在第二個循環中關閉原始流程並啟動一個新流程即可解決問題。 我不確定在我的特定情況下是否需要if __name__ == '__main__' ,因為這個腳本不打算為其他任何東西導入,但我只是遵循了multiprocessing文檔的指導。

暫無
暫無

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

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