2012-11-27 51 views
1

嗨我正在使用串行端口通信到我的設備之一使用python代碼。它發送一組十六進制代碼,接收一組數據。處理它。閱讀串行端口中的子進程閱讀

此數據必須存儲在數據庫中。

我有另一個腳本,它有MYSQLdb庫推送到數據庫。

如果我在一個腳本中按順序執行此操作,那麼我會在採樣率上損失很多。如果我不連接到數據庫並將其插入到表中,我可以每秒最多采樣32個數據集。

如果我使用Multiprocessing並嘗試運行它,那麼我的採樣率會變爲0.75,因爲父進程正在等待孩子加入。所以我該如何處理這種情況。

是否可以通過使用隊列填充數據來獨立運行它們?

+0

不知道你的意思是「等待孩子加入」 – scytale

回答

1

使用線程和隊列。

這裏有一個例子:

from Queue import Queue 
import threading 
import serial 

def readline(ser,output): 
    threadLock.acquire()# Get lock to synchronize threads 
    output.put(ser.readline()) 
    threadLock.release()# Free lock to release next thread 
    # this will go on forever until you kill the program 

if __name__=='__main__': 
    output = Queue() 
    with serial.Serial(com,baudrate=115200,timeout=1) as ser: 
     ser_thread = threading.Thread(target=readline, args=(ser,output,)) 
     ser_thread.start() 
     while(True): 
      threadLock.acquire()#wait until lock is free 
      try: 
       data=output.get() 
      threadLock.release()# Free lock to release next thread 
      # do somthing with data 
0

使用管道。 使用subprocess模塊完成兩個進程,第一個從串口讀取數據並將一組十六進制代碼寫入stdout。這是通過管道傳遞到從stdin讀取並更新數據庫的第二個進程。

+0

我在每個工藝製造的隊列,並通過雙方父母和子女之間的數據。它工作得很好。關鍵部分是引入更短的超時時間,以保持採樣率。 – Sri