我可以以某种方式避免在此脚本中使用time.sleep()吗?

时间:2016-08-07 05:18:50

标签: python gpsd

我有以下python脚本:

#! /usr/bin/python

import os
from gps import *
from time import *
import time
import threading
import sys

gpsd = None #seting the global variable

class GpsPoller(threading.Thread):
   def __init__(self):
      threading.Thread.__init__(self)
      global gpsd #bring it in scope
      gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
      self.current_value = None
      self.running = True #setting the thread running to true

   def run(self):
      global gpsd
      while gpsp.running:
         gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer

if __name__ == '__main__':
   gpsp = GpsPoller() # create the thread
   try:
      gpsp.start() # start it up
      while True:

         print gpsd.fix.speed

         time.sleep(1) ## <<<< THIS LINE HERE

   except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
      print "\nKilling Thread..."
      gpsp.running = False
      gpsp.join() # wait for the thread to finish what it's doing
   print "Done.\nExiting."

不幸的是,我对python并不是很好。脚本应该以某种方式多线程(但这可能与此问题的范围无关)。

令我感到困惑的是gpsd.next()行。如果我说得对,它应该告诉脚本已经获取了新的gps数据并准备好被读取。

但是,我使用无限while True循环读取数据,并使用time.sleep(1)暂停1秒。

然而,它的作用是它有时会回显两次相同的数据(传感器在最后一秒没有更新数据)。我认为它也会以某种方式跳过一些传感器数据。

我可以以某种方式更改脚本以不是每秒打印当前速度,但每次传感器报告新数据时?根据数据表,它应该是每秒(1 Hz传感器),但显然不是1秒钟,而是以毫秒为单位。

2 个答案:

答案 0 :(得分:2)

作为通用设计规则,每个输入通道应该有一个线程,或者对于阻塞调用中的每个&#34;循环,应该更通用。#34;阻止意味着执行在该呼叫停止,直到数据到达。例如。 gpsd.next()就是这样一个电话。

要同步多个输入通道,请使用Queue和一个额外的线程。每个输入线程都应该放置它的&#34;事件&#34;在(相同)队列上。额外的线程在queue.get()上循环并做出适当的反应。

从这个角度来看,你的脚本不需要是多线程的,因为只有一个输入通道,即gpsd.next()循环。

示例代码:

from gps import *

class GpsPoller(object):
   def __init__(self, action):
      self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
      self.action=action

   def run(self):
      while True:
         self.gpsd.next()
         self.action(self.gpsd)

def myaction(gpsd):
    print gpsd.fix.speed

if __name__ == '__main__':
   gpsp = GpsPoller(myaction)
   gpsp.run() # runs until killed by Ctrl-C

请注意action回调的使用如何将管道与数据评估分开。

要将轮询器嵌入到执行其他操作的脚本中(也就是处理其他线程),请使用队列方法。示例代码,基于GpsPoller类:

from threading import Thread
from Queue import Queue

class GpsThread(object):
    def __init__(self, valuefunc, queue):
        self.valuefunc = valuefunc
        self.queue = queue
        self.poller = GpsPoller(self.on_value)

    def start(self):
        self.t = Thread(target=self.poller.run)
        self.t.daemon = True  # kill thread when main thread exits
        self.t.start()

    def on_value(self, gpsd):
        # note that we extract the value right here.
        # Otherwise it could change while the event is in the queue.
        self.queue.put(('gps', self.valuefunc(gpsd)))


def main():
    q = Queue()
    gt = GpsThread(
            valuefunc=lambda gpsd: gpsd.fix.speed,
            queue = q
            )
    print 'press Ctrl-C to stop.'
    gt.start()
    while True:
        # blocks while q is empty.
        source, data = q.get()
        if source == 'gps':
            print data

&#34;行动&#34;我们给GpsPoller说&#34;通过valuefunc计算一个值并将其放入队列&#34;。主循环坐在那里直到一个值弹出,然后打印并继续。

将其他Thread事件放在队列中并添加适当的处理代码也很简单。

答案 1 :(得分:1)

我在这里看到两个选项:

  1. GpsPoller将检查数据是否已更改并引发标记
  2. GpsPoller将检查更改的id数据并将新数据放入队列。
  3. 选项#1:

    global is_speed_changed = False
    
    def run(self):
          global gpsd, is_speed_changed
          while gpsp.running:
             prev_speed = gpsd.fix.speed
             gpsd.next()
             if prev_speed != gpsd.fix.speed
                is_speed_changed = True  # raising flag
    
    while True:
            if is_speed_changed:
               print gpsd.fix.speed
               is_speed_changed = False
    

    选项#2(我更喜欢这个,因为它保护我们免受提升条件):

    gpsd_queue = Queue.Queue()
    
    def run(self):
          global gpsd
          while gpsp.running:
             prev_speed = gpsd.fix.speed
             gpsd.next()
             curr_speed = gpsd.fix.speed
             if prev_speed != curr_speed:
                gpsd_queue.put(curr_speed) # putting new speed to queue
    
    while True:
        # get will block if queue is empty 
        print gpsd_queue.get()