需要的取用,也是笔记,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.ite