两个同时运行的Python循环合成一个结果

1 投票
3 回答
629 浏览
提问于 2025-04-17 03:18

我现在有一段Python 2.6的代码,它可以同时运行两个循环。这个代码使用了gps(gpsd)模块和scapy模块。简单来说,第一个函数(gpsInfo)是一个持续运行的循环,它从GPS设备获取数据,并把位置信息打印到控制台。第二个函数(ClientDetect)也是一个持续运行的循环,它在空中嗅探wifi数据,并在找到特定的数据包时打印这些信息。我把这两个循环放在了不同的线程里,GPS的那个线程在后台运行。我现在想做的是,当ClientDetect函数找到匹配的wifi信号并打印相关信息时,我也想把当时的GPS坐标打印到控制台。现在我的代码似乎没有正常工作。

observedclients = [] p = ""  # Relate to wifi packet session =
gps.gps(mode=gps.WATCH_NEWSTYLE)

def gpsInfo():

    while True:
        session.poll()
        time.sleep(5)
        if gps.PACKET_SET:
            session.stream
            print session.fix.latitude + session.fix.longitude
            time.sleep(0.1)

def WifiDetect(p):
    if p.haslayer(Dot11):
        if p.type == 0 and p.subtype in stamgmtstypes:
            if p.addr2 not in observedclients:
                print p.addr2
                observedclients.append(p.addr2)  

def ActivateWifiDetect():
    sniff(iface="mon0", prn=WifiDetect)

if __name__ == '__main__':
    t = threading.Thread(target=gpsInfo)
    t.start()
    WifiDetect()

有没有人能看看我的代码,帮我想想怎么才能在找到wifi信号时,同时获取GPS坐标并打印出来?有人提到过使用队列,但我查了很多资料,还是不知道该怎么实现。

正如所说,这段代码的目的是扫描GPS和特定的wifi数据包,当检测到时,打印与数据包和检测位置相关的详细信息。

3 个回答

1

我觉得你应该更明确一下你的目标。

如果你只是想在检测到Wifi网络时获取GPS坐标,那你可以这样做(伪代码):

while True:
    if networkSniffed():
        async_GetGPSCoords()

如果你想记录所有的GPS坐标,并且想把这些坐标和Wifi网络的数据进行匹配,那你就把所有的数据和时间戳一起打印出来,然后再进行后期处理,通过时间戳把Wifi网络和GPS坐标对应起来。

1

当你在一个函数里使用gps这个外部变量时,需要告诉Python你要使用它。代码应该像这样:

def gpsInfo():
    global gps # new line

    while True:
        session.poll()
        time.sleep(5)
        if gps.PACKET_SET:
            session.stream
            print session.fix.latitude + session.fix.longitude
            time.sleep(0.1)


def WifiDetect(p):
    global p, observedclients # new line

    if p.haslayer(Dot11):
        if p.type == 0 and p.subtype in stamgmtstypes:
            if p.addr2 not in observedclients:
                print p.addr2
                observedclients.append(p.addr2)  
2

一个简单的方法是把GPS位置存储在一个全局变量中,然后让WiFi监听的线程在需要打印一些数据时读取这个全局变量。需要注意的是,因为两个线程可能会同时访问这个全局变量,所以你需要用一个互斥锁来保护它。

last_location = (None, None)
location_mutex = threading.Lock()

def gpsInfo():
    global last_location
    while True:
        session.poll()
        time.sleep(5)
        if gps.PACKET_SET:
            session.stream
            with location_mutex:
                # DON'T Print from inside thread!
                last_location = session.fix.latitude, session.fix.longitude
            time.sleep(0.1)

def WifiDetect(p):
    if p.haslayer(Dot11):
        if p.type == 0 and p.subtype in stamgmtstypes:
            if p.addr2 not in observedclients:
                with location_mutex:
                    print p.addr2, last_location
                    observedclients.append((p.addr2, last_location))  

撰写回答