Argparse
Argparse
Open in app
You have 1 free member-only story left this month. Upgrade for unlimited access.
Member-only story
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 1/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
Installation
Since argparse is part of the standard Python library, it should already be
installed. However, if it’s not, you can install it using the follwing command:
If you do not have pip installed, follow the installation docs here.
Getting Started
Here is a file called hello.py to demonstrate a very basic example of the
structure and usage of the argparse library:
# Add an argument
parser.add_argument('--name', type=str, required=True)
name of the command line field. The type is the variable type that is
expected as an input, and the required parameter is a boolean for whether
or not this command line field is mandatory or not. The actual arguments
can be accessed with args.name , where name is the name of the argument
identified in add_argument() .
As you can see, this will throw an error because the required name argument
is missing. This is the result when you include --name :
Hello, Sam
Positional Arguments
Sometimes, you don’t want to use the flag’s name in the argument. You can
use a positional argument to eliminate the need to specify the --name flag
before inputting the actual value. Below are two versions — the first without
positional arguments ( multiply.py ), and the second using positional
arguments ( multiply_with_positional.py ).
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=int, required=True)
parser.add_argument('--y', type=int, required=True)
args = parser.parse_args()
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 3/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
Output
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('x', type=int)
parser.add_argument('y', type=int)
args = parser.parse_args()
Output
Product: 20
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 4/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
Now, when you run your program with the help flag -h , you can see these
details.
Optional Arguments
Optional arguments are useful if you want to give the user a choice to enable
certain features. To add an optional argument, simply omit the required
parameter in add_argument() .
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--name', type=str, required=True)
parser.add_argument('--age', type=int)
args = parser.parse_args()
if args.age:
print(args.name, 'is', args.age, 'years old.')
else:
print('Hello,', args.name + '!')
Here we see two arguments: a name, which is required, and an optional age.
(Notice the required=True is missing from the --age argument.)
The two outputs below show the execution when --age is included and
when it is not.
With Optional Argument
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 5/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
In this example named sum.py , the --value argument takes in 3 integers and
will print the sum.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--values', type=int, nargs=3)
args = parser.parse_args()
sum = sum(args.values)
print('Sum:', sum)
Output
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 6/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
What if you don’t want just 3 values, but any number of inputs? You can set
nargs='+' , which will allow the argument to take in any number of values.
Using the same example above, with the only change being nargs=3 to
nargs='+' , you can run the script with however many input values you want.
Sum: 30
C:/> python sum.py --values 1 2 3 4 5 6 7 8 9 10
Sum: 55
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--add', action='store_true')
group.add_argument('--subtract', action='store_true')
parser.add_argument('x', type=int)
parser.add_argument('y', type=int)
args = parser.parse_args()
if args.add:
sum = args.x + args.y
print('Sum:', sum)
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 7/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
elif args.subtract:
difference = args.x - args.y
print('Difference:', difference)
The output example below shows what happens when you try to call --add
Output
Sum: 3
C:/> python mutually_exclusive.py --subtract 4 3
Difference: 1
C:/> python mutually_exclusive.py --add --subtract 4 3
As you can see from the error message, the script does not allow for --add
Subparsers
The last argparse feature I am going to discuss is subparsers. Subparsers are
powerful in that they allow for different arguments to be permitted based on
the command being run. For example, when using the git command, some
options are git checkout , git commit , and git add . Each one of these
commands requires a unique set of arguments, and subparsers allow you to
distinguish between them.
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 8/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
import argparse
parser = argparse.ArgumentParser()
subparser = parser.add_subparsers(dest='command')
login = subparser.add_parser('login')
register = subparser.add_parser('register')
args = parser.parse_args()
if args.command == 'login':
print('Logging in with username:', args.username,
'and password:', args.password)
elif args.command == 'register':
print('Creating username', args.username,
'for new member', args.firstname, args.lastname,
'with email:', args.email,
'and password:', args.password)
We create two separate subparsers — one for “login” and one for “register”.
This allows us to add individual arguments to each. Here, the “login”
subparser requires a username and a password. The “register” subparser
takes in a first and last name, a username, an email, and a password.
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 9/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
Login
Register
Takeaways
The goal of this post was to give a brief and relevant overview of the Python
library argparse . Code cleanliness and reusability is extremely valuable
these days, and argparse can help developers write more modular scripts
when requiring user input and interaction.
Thank you all for reading — I hope that I was able to improve your
understanding of argparse , and that you can utilize it in your next project!
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 10/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
Join Medium with the link below to support thousands of other writers and me.
Software Development
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 11/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
Follow
Engineer by day, writer by night. Follow for tech tutorials, productivity hacks, & psychology tricks
to help you get ahead of the curve & win the game of life.
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 12/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
167 3
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 13/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
515 6
692 9
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 14/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
57 1
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 15/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
6.7K 67
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 16/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
2K 21
Lists
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 17/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
JP Brown
26K 314
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 18/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
692 9
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 19/20
7/1/23, 11:04 AM A Simple Guide To Command Line Arguments With ArgParse | by Sam Starkman | Towards Data Science
4.5K 99
https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3 20/20