argparse Python
Introduction
This article is about the library
argparse
for working with arguments that are passed to a script from outside. For example, from the terminal.
Passing arguments to a script is a common practice for CI/CD.
To read about ordinary arguments, that is, the ones passed to a function inside a module, see the article
*args, **kwargs
To read about using
sys.argv[]
without wrappers, see
here
The techniques used here can be learned from the following articles:
Exceptions
,
Context manager
,
Lists
,
Strings
,
Working with files
Example
import argparse parser = argparse.ArgumentParser() parser.add_argument("filename", help="file to read") args = parser.parse_args() print(args)
python argparse_demo.py site.txt
Namespace(filename='site.txt')
filename ended up in Namespace because by default the action (action="store") is performed on every argument
It could have been specified explicitly as follows:
import argparse parser = argparse.ArgumentParser() parser.add_argument("filename", action="store", help="file to read") …
If no arguments are passed
python argparse_demo.py
usage: argparse_demo.py [-h] filename argparse_demo.py: error: the following arguments are required: filename
If an extra argument is passed
python argparse_demo.py site.txt demo.txt
usage: argparse_demo.py [-h] filename argparse_demo.py: error: unrecognized arguments: demo.txt
You can get help on an argument with the option -h
python argparse_demo.py -h filename
usage: argparse_demo.py [-h] filename positional arguments: filename file to read options: -h, --help show this help message and exit
version
The method add_argument() has several key arguments.
version is one of them.
Usually this action action="version" is used together with the flag
--version
A script called with a flag that has action="version" will not run through the standard scenario.
Instead, the value of the argument version,
which can be formed in a certain way.
The word version is very overloaded here. To avoid confusion, let us note once again:
--version - this is the flag that is used when calling the script.
action="version" - indicates that the action this flag performs is no longer store but version
version="%(prog)s 2.0" - indicates exactly how to print the version.
# argparse_version.py import argparse parser = argparse.ArgumentParser(description="version action demo", prog="PROG") parser.add_argument("--version", "-v", action="version", version="%(prog)s 2.0") args = parser.parse_args() print(args)
If you do not set prog= the file name will be used.
python argparse_version.py --version
PROG 2.0
We see that after the version was printed, Namespace() was not printed, because the script did not run the default scenario.
In the next chapter we will look at optional arguments with the default action="store"
Optional argument
To show that an argument is optional, two hyphens are added before its name --.
Such an argument is often called a flag. Usually after the long version
with two hyphens, a short one-letter version with a single hyphen is added after a comma -.
This is a standard practice that is not limited to Python scripts, but is used almost everywhere.
A typical example of such an argument in many scripts is --version, -v
Let us add two optional arguments: --limit and --version
# reverse_file.py import argparse parser = argparse.ArgumentParser(description='Reverse a file') parser.add_argument( "filename", action="store", help="the file to read") parser.add_argument( "--limit", "-l", action="store", type=int, help="the number of lines to read" ) parser.add_argument( "--version", "-v", action="version", version="%(prog)s 1.0" ) args = parser.parse_args() print(args)
This script cannot be run without the required argument filename
Apart from the case when the call is made with the flag --version
python reverse_file.py --version
reverse_file.py 1.0
But you can safely run the script without passing --limit
python reverse_file.py sites.txt
Namespace(filename='sites.txt', limit=None)
By default --limit got None.
About --version there are no mentions in Namespace.
--version is not an ordinary argument, because it has the option action="version" rather than action="store" as with .
You can pass the optional argument --limit in the following original way:
python reverse_file.py sites.txt -l 10
Namespace(filename='sites.txt', limit=10)
You can pass --limit as a string if it is convertible to int
python reverse_file.py sites.txt -l "5"
Namespace(filename='sites.txt', limit=5)
If the argument is not convertible to int we get an error
python reverse_file.py sites.txt -l "a"
usage: reverse_file.py [-h] [--limit LIMIT] [--version] filename reverse_file.py: error: argument --limit/-l: invalid int value: 'a'
Let us add functionality to the script that rewrites a file back to front.
import argparse parser = argparse.ArgumentParser(description='Reverse a file') parser.add_argument("filename", help="file to read") parser.add_argument("--limit", "-l", type=int, help="number of lines to read" ) parser.add_argument( "--version", "-v", action="version", version="%(prog)s 1.0" ) args = parser.parse_args() with open(args.filename) as f: lines = f.readlines() lines.reverse() if args.limit: lines = lines[:args.limit] for line in lines: print(line.strip()[::-1])
Note that after parsing the passed arguments are available as attributes of the object args
Let us apply the script to the file sites.txt
andreyolegovich.ru aredel.com devhops.site heihei.ru testsetup.site topbicycle.ru
python reverse_file.py sites.txt
ur.elcycibpot ur.putestset ur.iehieh ur.spohved moc.ledera ur.hcivogeloyerdna
Let us apply the flag --limit
python reverse_file.py sites.txt --limit 3
ur.elcycibpot ur.putestset ur.iehieh
Now, when we want to read a real file, we may encounter its absence
python reverse_file.py none.txt
Traceback (most recent call last): File "C:\python\reverse_file_form.py", line 14, in <module> with open(args.filename) as f: ^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'none.txt'
It is desirable to prepare for this in advance with an explicit
file existence check
or
try
About
the context manager (with)
you can read
here
import argparse parser = argparse.ArgumentParser(description='Reverse a file') parser.add_argument("filename", help="file to read") parser.add_argument("--limit", "-l", type=int, help="number of lines to read" ) parser.add_argument( "--version", "-v", action="version", version="%(prog)s 1.0" ) args = parser.parse_args() try: f = open(args.filename) except FileNotFoundError as e: print(e) else: with f: lines = f.readlines() lines.reverse() if args.limit: lines = lines[:args.limit] for line in lines: print(line.strip()[::-1])
python reverse_file.py none.txt
[Errno 2] No such file or directory: 'none.txt'
Exit Statuses
In the previous chapter we handled the error with a missing file using try
python reverse_file.py none.txt
[Errno 2] No such file or directory: 'none.txt'
The file was not found, but the script ran correctly. If we check the status now, it will be successful.
For example, in
PowerShell
:
echo $?
True
In Bash
echo $?
0
Such a result may not suit us. For example, we need the CI script that called our module to get an explicit error status and take the corresponding actions.
To solve this task, sys.exit
import argparse import sys parser = argparse.ArgumentParser(description='Reverse a file') parser.add_argument("filename", help="file to read") parser.add_argument("--limit", "-l", type=int, help="number of lines to read" ) parser.add_argument( "--version", "-v", action="version", version="%(prog)s 1.0" ) args = parser.parse_args() try: f = open(args.filename) except FileNotFoundError as e: print(e) sys.exit(2) else: with f: lines = f.readlines() lines.reverse() if args.limit: lines = lines[:args.limit] for line in lines: print(line.strip()[::-1])
python reverse_file.py none.txt
[Errno 2] No such file or directory: 'none.txt'
echo $?
False
echo $?
2
Default values
To set default values, the argument default.
An example of a script that gets an IP address and a port to make a request, but also has default values.
import requests import argparse parser = argparse.ArgumentParser() parser.add_argument("--ip", nargs="?", default="10.8.1.101", type=str) parser.add_argument("--port", nargs="?", default="5000", type=str) args = parser.parse_args() r = requests.get(f"http://{args.ip}:{args.port}/health") print(r.status_code)
Article author: Andrei Olegovich