2012-11-27 50 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