两个并发的Python循环和一个resu

2024-09-28 20:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一段Python2.6代码,可以同时运行两个循环。代码使用gps(gpsd)模块和scapy模块。基本上,第一个函数(gpsInfo)包含一个连续的while循环,从GPS设备获取GPS数据并将位置写入控制台。第二个函数(ClientDetect)在一个连续的循环中运行,它还可以嗅出空气中的wifi数据,并在找到特定数据包时打印这些数据。我已经把这两个循环与GPS一作为背景线程运行。我想做的是(已经花了5天的时间来解决这个问题)是为了,当ClientDetect函数找到匹配项并打印出相应的信息时,我希望在控制台上也能打印出命中的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包,当检测到时,打印与包相关的详细信息和检测到的位置。在


Tags: 模块数据函数代码ifsessiondefwifi
3条回答

一个简单的方法是将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))  

在函数中使用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)  

我认为你的目标应该更具体些。在

如果你只想在监听Wifi网络时获取GPS坐标,只需执行(psuedo代码):

while True:
    if networkSniffed():
        async_GetGPSCoords()

如果你想要一个所有GPS坐标的日志,并想将其与Wifi网络数据进行匹配,只需将所有数据与时间戳一起打印出来,然后进行后处理,通过时间戳将Wifi网络与GPS坐标进行匹配。在

相关问题 更多 >