Automate everyday tasks with Python · Lesson 13 of 14
Command-line scripts
Turn a script into a real command-line tool: read options with sys.argv and argparse, add a dry-run switch and log what happens.
A script becomes much more useful when you can change what it does without editing the code: which folder to tidy, how many days of backups to keep, whether to do a dry run. On your computer you give these arguments when you start the script from a terminal, for example python tidy.py downloads --days 30 --dry-run.
Python puts the words typed after python into the list sys.argv. The first item is the script's own name, the rest are the arguments, always as strings. This only makes sense when you start the script yourself, so try it on your computer: save the code below as args.py and run it from a terminal in the same folder.
# args.py run with: python args.py downloads 30
import sys
print(sys.argv) # ['args.py', 'downloads', '30']
if len(sys.argv) < 3:
print("usage: python args.py FOLDER DAYS")
sys.exit(1)
folder = sys.argv[1]
days = int(sys.argv[2]) # arguments are strings: convert numbers yourself
print(f"tidying {folder}, keeping {days} days")Runs in your own terminal. Here the comments show what it prints.
argparse: options with names
Checking sys.argv by hand gets messy quickly. The argparse module does it for you: you describe the arguments once, and it converts types, fills in defaults and writes a help text (python tidy.py --help). parse_args() normally reads sys.argv, but you can also hand it a list, which is how we test it on this page.
import argparse
parser = argparse.ArgumentParser(prog="tidy", description="Sort files into folders.")
parser.add_argument("folder", help="the folder to tidy")
parser.add_argument("--days", type=int, default=30, help="keep files newer than this")
parser.add_argument("--dry-run", action="store_true", help="only show what would happen")
args = parser.parse_args(["downloads", "--days", "7", "--dry-run"])
print(args.folder, args.days, args.dry_run)
args = parser.parse_args(["photos"])
print(args.folder, args.days, args.dry_run)downloads 7 True photos 30 False
- A name without dashes (
folder) is a positional argument: required, given by its place. - A name with
--is an option: optional, given by name, with adefault. type=intconverts the text to a number.action="store_true"makes a switch that isFalseunless it is given.--dry-runbecomesargs.dry_run: dashes turn into underscores.choiceslimits an option to a few values,nargs="*"collects any number of values into a list. A wrong value makes argparse print a short error and stop, so your code only ever sees valid input.
import argparse
parser = argparse.ArgumentParser(prog="report")
parser.add_argument("--format", choices=["csv", "json", "txt"], default="csv")
parser.add_argument("--ext", nargs="*", default=[], help="extensions to include")
args = parser.parse_args(["--format", "json", "--ext", "pdf", "docx"])
print(args.format, args.ext)
print(parser.parse_args([]).format)json ['pdf', 'docx'] csv
Logging instead of print
For messages about what a script is doing, use logging. Each message has a level: DEBUG, INFO, WARNING, ERROR. You choose the lowest level to show, so you can switch the details on or off without deleting lines. basicConfig sets the format; here we send it to normal output and leave out the time, so the example always prints the same. In a real script you would add %(asctime)s to the format to get the date and time on every line, and filename="tidy.log" to write the messages into a file.
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)-7s %(message)s",
stream=sys.stdout, force=True)
log = logging.getLogger("tidy")
log.debug("checking photo.jpg") # hidden: below INFO
log.info("moved %s to %s", "photo.jpg", "images")
log.warning("skipped %s: name already taken", "report.pdf")
log.error("could not read %s", "broken.zip")INFO moved photo.jpg to images WARNING skipped report.pdf: name already taken ERROR could not read broken.zip
Putting it together: main(argv)
A good pattern is a main() function that takes the argument list and returns an exit code: 0 for success, anything else for a problem. Other programs (and schedulers) read that code to know whether the run worked. Because main() takes a list, you can test it with different arguments.
import argparse
import logging
import sys
from pathlib import Path
log = logging.getLogger("tidy")
def main(argv):
parser = argparse.ArgumentParser(prog="tidy")
parser.add_argument("folder")
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args(argv)
level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(level=level, format="%(levelname)s: %(message)s", stream=sys.stdout, force=True)
folder = Path(args.folder)
if not folder.is_dir():
log.error("%s is not a folder", args.folder)
return 1
files = sorted(p.name for p in folder.iterdir() if p.is_file())
for name in files:
log.debug("found %s", name)
log.info("%d files in %s%s", len(files), args.folder, " (dry run)" if args.dry_run else "")
return 0
print("exit code", main(["inbox", "--dry-run"]))
print("exit code", main(["inbox", "--verbose"]))
print("exit code", main(["nowhere"]))INFO: 2 files in inbox (dry run) exit code 0 DEBUG: found a.txt DEBUG: found b.pdf INFO: 2 files in inbox exit code 0 ERROR: nowhere is not a folder exit code 1
To run the script on a schedule, end the file with sys.exit(main(sys.argv[1:])) and let the system start it: Task Scheduler on Windows (create a basic task that runs python with the script path as argument), cron on macOS and Linux (crontab -e, then a line with the time and the command). Always test the exact command in a terminal first, with --dry-run.
import sys
def main(argv):
... # the code from above
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
# cron (macOS / Linux), every Monday at 08:00:
# 0 8 * * 1 python3 /home/anna/scripts/tidy.py /home/anna/Downloads
# Task Scheduler (Windows): program python
# arguments C:\scripts\tidy.py C:\Users\anna\DownloadsFor your own computer. sys.argv[1:] drops the script name.
✎ Exercise
Build a parser named backup with a positional source, an option --keep (an int, default 5) and a switch --zip. Parse the list ["photos", "--zip"] and print the three values, then parse ["music", "--keep", "2"] and print them again.
Hint: Positional: add_argument("source"). Option: add_argument("--keep", type=int, default=5). Switch: action="store_true".
import argparse
# your code here
Expected output:
photos 5 True music 2 False
Show a solution
import argparse
parser = argparse.ArgumentParser(prog="backup")
parser.add_argument("source")
parser.add_argument("--keep", type=int, default=5)
parser.add_argument("--zip", action="store_true")
for argv in (["photos", "--zip"], ["music", "--keep", "2"]):
args = parser.parse_args(argv)
print(args.source, args.keep, args.zip)photos 5 True music 2 False
Check yourself
1. What is sys.argv[0]?
The script name comes first; the real arguments start at sys.argv[1].
2. What does action="store_true" create?
Without the switch the value is False; typing --dry-run makes it True.
3. With level=logging.INFO, which message is hidden?
DEBUG is below INFO, so it is not shown.