python 的动态参数解析器

问题描述 投票:0回答:1

我正在构建一个小型包装器,它可以接受 python 命令动态推断参数及其相关值。我想要类似 arg 解析器的东西,但要注意的是我事先不知道参数。例如,我可以作为输入:

python some_script.py --arg1 val1 --arg2 val2 --arg3 val3

我想要一些字典

{arg1: val1, arg2: val2, arg3: val3}

python argparse
1个回答
0
投票

你可以这样做:

import argparse
import sys

# Create an ArgumentParser object
parser = argparse.ArgumentParser()

# Add arguments to the parser dynamically based on the command-line arguments
for arg in sys.argv[1:]:
    if arg.startswith('--'):
        # Get the argument name and add it to the parser
        arg_name = arg[2:]
        parser.add_argument(arg, dest=arg_name)

# Parse the command-line arguments
args = parser.parse_args()

# Access the values of the arguments as a dictionary
arg_dict = args.__dict__

print(args_dict)

>> {'test': '0', 'test2': '1'}
© www.soinside.com 2019 - 2024. All rights reserved.