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

如何从后台运行的Python脚本中获取gps_time变量?

Python跨脚本共享GPS时间变量的实现方案

下面是几种实用的方法,帮你从前台脚本获取后台GPS脚本的gps_time变量:

方法1:本地文件读写(最简单易实现)

后台脚本定期将最新的gps_time写入本地文本文件,前台脚本读取该文件内容。

后台GPS脚本(gps_background.py)

import time

# 替换成你实际的GPS时间获取逻辑
def fetch_gps_time():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

if __name__ == "__main__":
    while True:
        current_gps_time = fetch_gps_time()
        # 写入文件覆盖旧内容
        with open("gps_time_cache.txt", "w") as f:
            f.write(current_gps_time)
        time.sleep(1)  # 刷新间隔可根据需求调整

前台查询脚本(query_gps.py)

while True:
    user_cmd = input("输入'查看'获取GPS时间,输入'退出'结束:")
    if user_cmd == "查看":
        try:
            with open("gps_time_cache.txt", "r") as f:
                gps_time = f.read().strip()
                print(f"当前GPS时间:{gps_time}")
        except FileNotFoundError:
            print("错误:GPS后台脚本未运行,请先启动后台服务")
    elif user_cmd == "退出":
        break
    else:
        print("输入无效,请重新输入")

注意:确保两个脚本在同一目录下,或者文件路径写绝对路径;如果后台脚本意外终止,文件可能不存在或内容过时。

方法2:基于Socket的进程间通信(适合完全独立的脚本)

后台脚本启动本地Socket服务,监听指定端口,前台脚本通过Socket连接请求获取最新时间。

后台GPS服务脚本(gps_server.py)

import socket
import time

def fetch_gps_time():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

if __name__ == "__main__":
    # 创建TCP Socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(("localhost", 12345))  # 绑定本地端口12345
    server.listen(5)
    print("GPS后台服务已启动,监听端口12345")

    while True:
        client_conn, addr = server.accept()
        # 返回最新GPS时间
        client_conn.send(fetch_gps_time().encode("utf-8"))
        client_conn.close()

前台查询客户端脚本(gps_client.py)

import socket

def get_gps_time():
    try:
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(("localhost", 12345))
        gps_time = client.recv(1024).decode("utf-8")
        client.close()
        return gps_time
    except ConnectionRefusedError:
        return None

if __name__ == "__main__":
    while True:
        user_cmd = input("输入'查看'获取GPS时间,输入'退出'结束:")
        if user_cmd == "查看":
            time_data = get_gps_time()
            if time_data:
                print(f"当前GPS时间:{time_data}")
            else:
                print("无法连接到GPS后台服务,请确认服务已启动")
        elif user_cmd == "退出":
            break
        else:
            print("输入无效,请重新输入")

优势:两个脚本完全独立,甚至可以跨机器通信(修改localhost为对应IP即可);需要处理连接异常情况。

方法3:使用multiprocessing共享内存(适合父子进程场景)

如果前台脚本可以启动后台GPS进程,用multiprocessing.Manager创建共享字典来传递变量。

整合脚本(前台启动后台进程)

import time
from multiprocessing import Process, Manager

def gps_worker(shared_data):
    # 模拟GPS时间获取
    while True:
        shared_data["gps_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        time.sleep(1)

if __name__ == "__main__":
    with Manager() as manager:
        shared_dict = manager.dict()
        # 启动后台GPS进程
        gps_process = Process(target=gps_worker, args=(shared_dict,))
        gps_process.daemon = True
        gps_process.start()

        # 前台查询逻辑
        while True:
            user_cmd = input("输入'查看'获取GPS时间,输入'退出'结束:")
            if user_cmd == "查看":
                if "gps_time" in shared_dict:
                    print(f"当前GPS时间:{shared_dict['gps_time']}")
                else:
                    print("GPS数据尚未就绪,请稍候")
            elif user_cmd == "退出":
                break
            else:
                print("输入无效,请重新输入")

优势:实时性好,无磁盘IO开销;缺点是两个进程必须由同一个父进程启动,无法完全独立运行。


内容的提问来源于stack exchange,提问作者Luca Rosignoli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:15:33