As your scripts start getting a bit more complex, it might be a challenge setting them up in a way that is consistent and predictable by others. Working with a script that requires different arguments each time you use it wouldn’t be very consistent and predictable.

Luckily, Python’s Standard Library comes with a module named Argparse that has a set of tools for parsing command-line arguments in your Python scripts.

Argparse allows you to define the arguments in a clean and organized way, and you can also set up helpful messages in order to help the user.

You can specify the name, type, default values for each argument and automatically generate usage messages which are very helpful when you want someone else to try your script or for debugging purposes.

I have recently used Argparse in my Anki automation script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import argparse

parser = argparse.ArgumentParser(description='Get noun/verb translation')

parser.add_argument('word', nargs='*', help='Word you wish to translate', type=str)
parser.add_argument('-t', default='noun', help='Type of word - noun or verb?', type=str)
parser.add_argument('-eng', default=False, help='Translate from German to English', type=bool)

args = parser.parse_args()

# Now I can access each argument
word_to_translate = args.word
word_type = args.t
to_eng = args.eng

In this example, we create an ArgumentParser object and use the add_argument() method to specify the arguments that our script expects. We can specify the type of each argument (e.g., int or str) as well as a default value and a help message.

Then, we use the parse_args() method to parse the command-line arguments that are passed to our script.

The resulting args object contains the values of the arguments as attributes, which we can access using dot notation (e.g., args.word).