1

我有兩個將數據提供給Python的串口。 一個是供給GPS串(每秒約4線) ,另一個從氣體監控器饋送的數據串(約1線每秒)在Python中異步監控兩(2)個串口端口

我想監視GPS和氣體進料在相同的時間和實時合併數據。我只需要接收串口的數據。

我的問題是,我似乎無法弄清楚如何讓兩個python函數同時運行。

我使用Python 2.7安裝了線程模塊和多處理模塊。

任何想法結合串行信息的好方法?這是我第三Python程序永遠所以請溫柔與我:-)

下面的代碼:

import threading 
import multiprocessing 

def readGas(): 
    global GAScount 
    global GASline 
    while GAScount<15: 
     GASline = gas.readline() 
     GasString = GASline.startswith('$') 
     if GasString is True: 
      print GASline 
     GAScount = GAScount+1 

def readGPS(): 
    global GPScount 
    global GPSline 
    while GPScount<50: 
     GPSline = gps.readline() 
     GPSstring = GPSline.startswith('$') 
     if GPSstring is True: 
      print GPSline 
     GPScount = GPScount+1 

openGPS() 
openGas() 

回答

0

我覺得線程將你的情況是不錯的選擇,因爲你不希望很高頻率。這將比多處理更簡單,因爲內存在線程之間保持共享,你不必擔心。 剩下的唯一問題是您的併購不會完全在同一時間,而是一個接一個。如果您確實需要同步數據,則需要使用多處理功能。

穿線:

import threading 

# create your threads: 
gps = threading.Thread(target=openGPS) 
gas=threading.Thread(target=openGas) 

#start your threads: 
gps.start() 
gas.start() 

你現在有2採集線程運行。由於python的全局解釋鎖,這不是同時適用,而是在兩個線程之間交替。

更多的信息穿線:https://pymotw.com/2/threading/ 更多的信息上GIL:https://wiki.python.org/moin/GlobalInterpreterLock

+0

感謝您的!和鏈接:-) – BraveSirRobin