Mutual conversion between Python argparse object and dict object

I. Introduction

        Python argparse is a built-in Python module for command item options and parameter parsing. This module makes it easy to write user-friendly command line interfaces and helps programmers define parameters for models.

        Examples of application scenarios. For example, if you write a Python code, the code has some parameters that cannot be determined in my program, but can only be determined when you call the Python file for execution. At this time, you can use argparse to show your talents.

        Use an example. After you have defined some parameter lists for your Python program, you can call the following script/command to execute your Python program:

python a_code.py --name "JACK Williams" --height 175.6 --weight 75

        Among them, "a_code.py" is the Python program you wrote, and "name", "height" and "weight" are the parameters that your program needs to use, and the values ​​of these parameters need to be determined during execution.

        Since we often use argparse, the Python built-in library, if there are many parameters in the program, we will inevitably want to save these parameters by saving them as files, so that if the program needs to call these next time parameters, we can quickly, automatically, and efficiently obtain the parameter values ​​that have been entered.

        Therefore, this blog provides a method for converting between argparse objects and dict objects. If you want to save these parameters and parameter values ​​​​to a file, you can first convert argparse to a dict object (this can also be considered as a simplified version of the json object, because dict only has key-value pairs), and then the dict object comes with Python json library to save it to a file. For the file reading and writing of json objects, you can refer to the Python json object - file reading and writing this blog.

        In this way, we can go from argparse to dict(json) to file , or from file to dict(json) to argparse .

Two, argparse to dict

        Idea: Define the parameter list in the Python program, then read the parameter list from the terminal to get the argparse object, and then convert the object into a dict object.

        1. Code: Define the parameter list in the Python program (including the conversion from argparse to dict), and the corresponding Python program file name here is "args2dict.py"

import argparse

# define arguments
def parse_args(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('--Name', type=str)
    parser.add_argument('--ID', type=int)
    parser.add_argument('--At_School', type=bool)
    parser.add_argument('--Math_Score', type=float)
    return parser.parse_args(args)

# program entrance
if __name__ == '__main__':
    # read args from the terminal
    an_args = parse_args()

    # transfer the args to a dict
    args_dict = vars(an_args)

    # use the dict
    for k in args_dict.keys():
        print(k, args_dict[k], type(args_dict[k]))

        2. Enter the parameter list when executing "args2dict.py" in the terminal, and the program will automatically convert the parameter list into a dict object after completion

python args2dict.py --Name "JACK Williams" --ID 391568 --At_School true --Math_Score 95.6

        3. The execution output of the program is as follows

Name JACK Williams <class 'str'>
ID 391568 <class 'int'>
At_School True <class 'bool'>
Math_Score 95.6 <class 'float'>

Three, dict to argparse

        Idea: Call the static method Namespace of argparse to automatically convert the key-value pairs of dict into argparse objects

        the code

import argparse

# create a dict object
a_student = {'Name': 'JACK Williams',
             'ID': 391568,
             'At_School': True,
             'Math_Score': 92.3}

# transfer the dict object to an ArgumentParser object
args = argparse.Namespace(**a_student)

# use the ArgumentParser object
print(args.Name, type(args.Name))
print(args.ID, type(args.ID))
print(args.At_School, type(args.At_School))
print(args.Math_Score, type(args.Math_Score))

        The output of this program is as follows

JACK Williams <class 'str'>
391568 <class 'int'>
True <class 'bool'>
92.3 <class 'float'>

4. Reference

        1. Pass in the parameters of argparse in the form of a dictionary

        2. Python uses the json library to read and write files of json objects

Guess you like

Origin blog.csdn.net/qq_36158230/article/details/128708924