Three methods of treating Args with Python are explained in detail

  • 2021-10-13 08:02:25
  • OfStack

1. sys module

The sys module in Python has argv functionality. When the execution of main. py is triggered by the terminal, this feature returns a list of all command-line arguments supplied to main. py. The first element in the return list, among other parameters, is the path to main. py.

Consider the following main. py example


import sys
list_of_arguments = sys.argv
print(list_of_args[0]) 
print(list_of_args[1]) 
print(list_of_args[2]) 
print(list_of_args[3])

Trigger main. py on the command line as follows:


python main.py first_arg "[second_arg]" "{\"arg\": 3}"

The output is as follows:

test.py
first_arg
[second_arg]
{"arg": 3}

2. sys Module with 1 Large Parameter

This is a simple and powerful way to provide parameters for Python code. You don't need to provide a large number of parameters separated by spaces, but provide a single 1 "large" parameter. This large parameter is a string dictionary where dict-keys represents the parameter name and dict-value represents the corresponding value.

Consider the following example of main. py


import sys
import ast
raw_arguments = sys.argv[1]
 
print(raw_arguments)
arguments = ast.literal_eval(raw_arguments)
 
print(arguments['name']) # John
print(arguments['surname']) # Doe
print(arguments['age']) # 22

main. py is triggered on the command line as follows:


python main.py "{\"name\": \"John\", \"surname\": \"Doe\", \"age\": 22}"

The output is as follows:

{"name": "John", "surname": "Doe", "age": 22}
John
Doe
22

3. argparse Module

If you want to provide an appropriate command-line interface for your application, argparse is the module you need.

This is a comprehensive module, which provides ready-made parameter parsing, help messages and automatic error throwing when misusing parameters.

To make full use of the functions provided by argparse, it takes some time to master. Now let's consider the following main. py example:


import argparse
parser = argparse.ArgumentParser(description='Personal information')
parser.add_argument('--name', dest='name', type=str, help='Name of the candidate')
parser.add_argument('--surname', dest='surname', type=str, help='Surname of the candidate')
parser.add_argument('--age', dest='age', type=int, help='Age of the candidate')
args = parser.parse_args()
print(args.name)
print(args.surname)
print(args.age)

After initializing the ArgumentParses object, we use the add_argument function to add all the expected parameters. This function takes a number of arguments, including the parameter name, the target variable, the expected data type, the help message to display, and so on.

main. py is triggered on the command line as follows:


python main.py --name John --surname Doe --age 22

The output is as follows:

John
Doe
22

We're just going to give you a brief introduction here. To learn more about this module, you can check the link https://docs.python.org/2/library/argparse.html.

Summarize

Most of the time, you need to pass the parameters to the Python script. Python provides access to these parameters through the sys module. You can access the argv function directly and handle parameter resolution yourself, or you can use other modules as argparse. For this site, it is usually used to using sys module, and what suits you is the best ~


Related articles: