json配置文件读入redis - 包含命令行解析示例

70 篇文章 0 订阅
39 篇文章 0 订阅

需要的取用,也是笔记,python argv经常会需要解析。类linux的命令行参数处理,这也是一个示例。 

1.源码

#!/usr/bin/python3
#using whereis python3 to get the location of your python cmd.
# -*- coding: utf-8 -*-
# 获取当前脚本文件所在目录的父目录,并构建相对路径
import os
import sys
import json
import redis
import argparse
current_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(current_dir, '..')
sys.path.append(project_path)
sys.path.append(current_dir)

def load_json_from_file(file_path):
    # 打开文件并读取内容
    with open(file_path, 'r', encoding='utf-8') as file:
        json_str = file.read()
    
    # 将 JSON 字符串解析为 Python 对象
    data = json.loads(json_str)
    
    return data

def json2redis(data, root_name='cfg', redis_host='localhost', redis_port=6379):
    # 连接到 Redis 服务器
    r = redis.Redis(host='localhost', port=6379, decode_responses=True)
    
    # 定义一个递归函数来遍历数据并存储到 Redis
    def store_in_redis(prefix, data):
        if isinstance(data, dict):
            for key, value in data.items():
                new_key = f"{prefix}:{key}"
                store_in_redis(new_key, value)
        elif isinstance(data, list):
            for index, item in enumerate(data):
                new_key = f"{prefix}:{index}"
                store_in_redis(new_key, item)
        else:
            r.set(prefix, data)
    
    # 调用函数,传入根键名
    store_in_redis(f"{root_name}", data)
    
    # 示例:从 Redis 获取存储的数据并打印
    for key in r.keys(f"{root_name}:*"):
        print(f"{key}: {r.get(key)}")

def main():
    # 创建 ArgumentParser 对象
    parser = argparse.ArgumentParser(description='json配置文件 => Redis')

    # 添加参数
    parser.add_argument('jsonfile', type=str, help='json_file_name, the src')
    parser.add_argument('--redis_ip', type=str, default='127.0.0.1', help='redis server ip')
    parser.add_argument('--redis_port', type=int, default=6379, help='redis server port')
    parser.add_argument('--verbose', action='store_true', help='启用详细模式')

    # 解析命令行参数
    args = parser.parse_args()

    # 使用参数
    print(f'输入文件: {args.jsonfile}')
    print(f'输出文件: {args.redis_ip}')
    print(f'处理次数: {args.redis_port}')
    print(f'详细模式: {"启用" if args.verbose else "禁用"}')
    
    json_obj = load_json_from_file(args.jsonfile)
    filename_without_ext, _ = os.path.splitext(args.jsonfile)
    root = filename_without_ext
    root = root.replace("/", ":")
    root = root.replace("\\", ":")
    print(root)
    json2redis(json_obj, root, args.redis_ip, args.redis_port)
    

if __name__ == '__main__':
    main()
  1. 做了脚本执行解释器的处理。
  2. 做了自动参数识别。
  3. 参数支持usage 和 --help打印。 

2.命令行

1.参数不全的命令行简介自动输出 ./daemon_exec 

usage: daemon_exec [-h] [--redis_ip REDIS_IP] [--redis_port REDIS_PORT] [--verbose] jsonfile
daemon_exec: error: the following arguments are required: jsonfile

2.细节的参数注释打印 ./daemon_exec  --help

usage: daemon_exec [-h] [--redis_ip REDIS_IP] [--redis_port REDIS_PORT] [--verbose] jsonfile

json配置文件 => Redis

positional arguments:
  jsonfile              json_file_name, the src

optional arguments:
  -h, --help            show this help message and exit
  --redis_ip REDIS_IP   redis server ip
  --redis_port REDIS_PORT
                        redis server port
  --verbose             启用详细模式

3.运行示例

:home:app:cfg:kde_ai_cfg:app:chDesc:2:video_stream_out: rtsp://127.0.0.1:8554/ch3
:home:app:cfg:kde_ai_cfg:hardware:ip:1:mode: static
:home:app:cfg:kde_ai_cfg:app:chDesc:1:classes_prefered:0: 0
:home:app:cfg:kde_ai_cfg:endpoint:aux:mqtt:0:server: 47.114.51.90
:home:app:cfg:kde_ai_cfg:hardware:ip:0:gateway: 192.168.0.1

 3.1 redis客户端的显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子正

thanks, bro...

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值