Skip to main content
 首页 » 编程设计

python之名称错误 : name 'altitude' is not defined

2025年05月04日10lovecherry

我有这个 gps 代码,它获取 gps 数据并写入日志:

#!/usr/bin/python 
 
from systemd import journal 
import gps 
import time 
import threading 
import datetime 
 
# Listen on port 2947 (gpsd) of localhost 
session = gps.gps("localhost", "2947") 
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) 
 
while True: 
    try: 
        report = session.next() # Wait for a 'TPV' report and display  
the current time 
 
        # To see all report data, uncomment the line below 
        #print report 
 
        if report['class'] == 'TPV': 
            if hasattr(report, 'time'): 
                timestamp = (time.time()*1000) 
                #print timestamp 
 
            if hasattr(report, 'lat'): 
                latitude = report.lat 
                #print latitude 
 
            if hasattr(report, 'lon'): 
                longitude = report.lon 
                #print longitude     
 
            if hasattr(report, 'alt'): 
                altitude = report.alt 
                #print altitude 
 
        else: 
            timestamp = (time.time()*1000) 
            latitude = 0 
            longitude = 0  
            altitude = 0 
 
        journal.send( 
        channel = 'gps', 
        priority = journal.Priority.INFO, 
        timestamp = "%f" % (timestamp), 
        latitude = "%f" % (latitude), 
        longitude = "%f" % (longitude),  
        altitude = "%f" % (altitude),  
        ) 
 
except KeyError: 
    pass 
except KeyboardInterrupt: 
    quit() 
except StopIteration: 
    session = None 
    print "GPSD has terminated" 

我得到这个错误:

Traceback (most recent call last): 
  File "gps-messi.py", line 57, in <module> 
    altitude = "%f" % (altitude), 
NameError: name 'altitude' is not defined 

有趣的是代码有时工作得很好,有时却给我这个错误。我不明白我应该怎么做才能让它一直正常工作。这和她的爆炸有什么关系吗?

请您参考如下方法:

我的猜测是 if hasattr(report, 'alt'): 没有解析为 True,那么

if hasattr(report, 'alt'): 
    altitude = report.alt 

不会为 altitude 分配任何东西,当你到达这里时就在那里

journal.send( 
    channel = 'gps', 
    priority = journal.Priority.INFO, 
    timestamp = "%f" % (timestamp), 
    latitude = "%f" % (latitude), 
    longitude = "%f" % (longitude),  
    altitude = "%f" % (altitude),  
    ) 

在分配之前,您实际上是在使用 altitude。为避免这种情况,您可以在到达此点之前将 altitude 初始化为某个值

altitude=0 

这样做将确保它在使用之前就已分配,并且您不应该得到该错误。