Python is an excellent language to create scripts that perform utility tasks, but to add flexibility to any script it needs to accept parameters.
Getting parameters is easy enough, using sys.argv
as illustrated in the example below.
import sys
# Ensure there are at least 3 arguments, of course 0 is our script name.
if len(sys.argv) < 3:
print("Usage: python script.py <name> <age>")
sys.exit(1)
# Storing command-line arguments in variables
script_name = sys.argv[0] # The script name
name = sys.argv[1] # First argument
age = sys.argv[2] # Second argument
print(f"Script Name: {script_name}")
print(f"Hello, {name}! You are {age} years old.")
Usage is simplistic, where you call the script with a parameter for name and age.
myscript.py John 32
But what if we wanted some more advanced operations, like named operations and if a certain operation requires additional arguments. Below is a slightly more advanced example that does the following:
- has a description for the script.
- takes in dashed options, Mode (-m, --m), Foo (-f, --foo)
- depending on the mode, a Foo is requred.
import argparse
# Create the parser
parser = argparse.ArgumentParser(description=
"""
Test script that takes in arguments.
A mode of 'A' requirest a -f parameter, while 'B' does not.
-f argument needs to be an integeger.
Example: test.py -m A -f 10
""", formatter_class=argparse.RawTextHelpFormatter)
# Add arguments
parser.add_argument('-m', '--mode', choices=['A', 'B'], help='Mode of operation')
parser.add_argument('-f', '--foo', type=int, help='An integer argument required if mode is A')
# Parse the arguments
args = parser.parse_args()
# Check if no arguments are provided
if not any(vars(args).values()):
parser.print_help()
parser.exit()
# Custom logic to enforce conditional requirement
if args.mode == 'A' and args.foo is None:
parser.error("-f is required when -m is 'A'")
# Access the arguments
print(f"Mode: {args.mode}")
print(f"Foo: {args.foo}")
Let's take a look at what the code does.
- I stepped away from using the
sys.argv
and useargparse
, which gives me more features. - I initialize my parser, and it has a description, which is a string block. I need to specify the
formatter_class
to allow python to use the raw string data in our string, otherwise the formatting is stripped out. - I add the arguments I want to look for into the parser; a
mode
which can be-m
or--mode
, and expect the choices to be A or B, I also provide some help text. - The next argument I want is my
foo
, which can be either a-f
or--foo
, it has to be an integer and I provide some help text. The help text is useful when the script isn't run properly, the help text is shown to the user along with the description. - When the arguments are properly provided, I interrogate the mode, and if it A I also require foo to be present, otherwise I error out.
- If everything is good, I print out the results.
Hopefully this helps show how you can add advanced parameter input for your script.