The best way to use command line arguments on your Python script is by using the argparse library.
Step By Step
First import the library
import argparse
The initialize a parser object
parser = argparse.ArgumentParser(description='Find out the number of World Cups By Country.')
Use the add_argument() function to add the prefix of your argument.
The choices parameter lets you input a number of options that will be displayed to the user in case the argument is invalid.
You can also specify if the argument is required or not.
Finally, you can set a help message to be displayed if the user uses the -h option.
parser.add_argument("--country",
choices=["brazil", "germany", "italy"],
required=True,
help="Inform your country")
Use the _parseargs() function to parse the arguments given in the command line.
Notice that I use the args.country because country is the name I defined in the add_argument() function to have access to the argument passed.
args = parser.parse_args()
country = args.country
Finally, you can execute some logic based on the argument received.
if country == "brazil":
print("5 World Cups")
elif country == "germany" or country == "italy":
print("4 World Cups")
The Whole Example
The complete script:
import argparse
parser = argparse.ArgumentParser(description='Find out the number of World Cups By Country.')
parser.add_argument("--country",
choices=["brazil", "germany", "italy"],
required=True,
help="Inform your country")
args = parser.parse_args()
country = args.country
if country == "brazil":
print("5 World Cups")
elif country == "germany" or country == "italy":
print("4 World Cups")
Save the script in a file named world_cup.py.
Run the script in the command line:
python world_cup.py
To get following error output:
usage: world_cup.py [-h] --country {brazil,germany,italy}
world_cup.py: error: argument --country is required
Ask for help:
python world_cup.py -h
And get help:
usage: world_cup.py [-h] --country {brazil,germany,italy}
Find out the number of World Cups By Country.
optional arguments:
-h, --help show this help message and exit
--country {brazil,germany,italy}
Inform your country
Finally, use it as it is supposed to be used.
python world_cup.py --country brazil
And get as output:
5 World Cups
That was a quick example of how to use command line arguments in Python, subscribe to learn more!