3 Ways to Handle Args in Python. A Straight to the Point Guide | by Dardan Xhymshiti | Towards Data Science

The sys module in Python has the argv functionality. This functionality returns a list of all command-line arguments provided to the main.py when triggering an execution of it through terminal. Besides other arguments, the first element in the returned list is the path to the main.py.
Consider the following example of main.py
import syslist_of_arguments = sys.argvprint(list_of_args[0]) print(list_of_args[1]) print(list_of_args[2]) print(list_of_args[3])
Triggering main.py as:
python main.py first_arg "[second_arg]" "{\"arg\": 3}"
would return:
test.pyfirst_arg[second_arg]{"arg": 3}
This is a simple yet powerful way to provide arguments to your Python code. Instead of providing a number of arguments split by space, you provide a single “big” argument. This one big argument is a stringified dictionary where dict-keys represent the argument names and dict-values represent their corresponding values.
Since this dictionary argument is represented as a string when read in Python, you should translate it to a dictionary. This can be done by using the ast.literal_eval or json.loads functionalities. ast or json modules need to be imported accordingly.
Consider the following example of main.py:
import sysimport astraw_arguments = sys.argv[1]print(raw_arguments)arguments = ast.literal_eval(raw_arguments)print(arguments['name']) # Johnprint(arguments['surname']) # Doeprint(arguments['age']) # 22
Triggering main.py as:
python main.py "{\"name\": \"John\", \"surname\": \"Doe\", \"age\": 22}"
would return:
{"name": "John", "surname": "Doe", "age": 22}JohnDoe22
If you want to have a proper command-line interface for your application, the argparse is the module to go. This is a full-fledge module that offers out-of the-box arguments parsing, help messages and automated error throwing when arguments get misused. This module comes pre-installed with Python.
To fully utilize the functionalities provided by argparse, it takes some time to master. As a start up, consider the following example of main.py:
import argparseparser = 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 an object of ArgumentParses, we add all the expected arguments by using add_argument function. This function receives a number of parameters among which the argument name (eg. --name), the destination variable, the expected data type, the help message to display etc.
Triggering main.py as:
python main.py --name John --surname Doe --age 22
would return
JohnDoe22
To find more about this module, take a look at argparse docs.
Many times you need to pass arguments to your Python scripts. Python provides access to these arguments through thesys module. You can directly access the argv functionality and handle the parse of arguments in your own, or you can use some other module as argparse that does that for you.
In my day-to-day coding life, I go with sys with one big argument in small scripts that I am the sole user/maintainer of them and argparse whenever I go for production-ready.