You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3连接gpsd守护进程报错,求维护版客户端或解决方案

解决Python3连接gpsd的问题

一、推荐维护中的Python3 gpsd客户端

  • gpsd-py3:这是专门适配Python3的gpsd客户端库,目前仍在维护。安装命令:pip install gpsd-py3,基础使用示例:
import gpsd

# 连接本地gpsd守护进程(默认端口2947)
gpsd.connect()

# 获取当前GPS数据包
packet = gpsd.get_current()

# 提取有效定位信息
if packet.mode >= 2:  # 至少获取到2D定位数据
    print(f"纬度: {packet.lat}, 经度: {packet.lon}")
    if packet.mode >= 3:  # 支持3D定位时获取海拔
        print(f"海拔: {packet.alt} 米")
else:
    print("未获取到有效GPS定位数据")

这个库修复了旧版本中JSONDecoder编码参数的兼容问题,完全适配Python3的json库API。

  • 原生套接字+json解析:如果不想依赖第三方库,可直接通过套接字连接gpsd,手动解析JSON格式的返回数据:
import socket
import json
import time

def get_gps_position():
    # 建立与gpsd的套接字连接
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("localhost", 2947))
    # 发送WATCH命令,开启数据推送
    sock.send(b'?WATCH={"enable":true,"json":true}\n')
    
    while True:
        data = sock.recv(1024).decode('utf-8')
        for line in data.split('\n'):
            if line.strip():
                try:
                    packet = json.loads(line)
                    # 筛选TPV类型的数据包(包含核心定位信息)
                    if packet['class'] == 'TPV' and 'lat' in packet and 'lon' in packet:
                        lat = packet['lat']
                        lon = packet['lon']
                        alt = packet.get('alt', None)
                        sock.close()
                        return (lat, lon, alt)
                except json.JSONDecodeError:
                    continue
        time.sleep(0.1)

# 使用示例
try:
    lat, lon, alt = get_gps_position()
    print(f"位置: 纬度 {lat}, 经度 {lon}")
    if alt is not None:
        print(f"海拔: {alt} 米")
except Exception as e:
    print(f"获取GPS数据失败: {e}")

这种方法直接对接gpsd的原生JSON协议,完全避开旧库的兼容问题,无需额外安装依赖。

二、修复官方示例的报错问题

你遇到的TypeError: JSONDecoder.__init__() got an unexpected keyword argument 'encoding',是因为旧代码沿用了Python2时代的写法——给json.JSONDecoder传入encoding参数,而Python3中该参数已被移除。

修复方式很简单:直接去掉encoding参数,或者改用json.loads()解析数据(Python3中json.loads默认支持utf-8编码)。

内容的提问来源于stack exchange,提问作者Al Grant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:22:43