Web App Development

Unnamed arguments with argparse

To pass arguments to Python scripts like this
python myscript file1.txt file2.py
you do
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("files",nargs="*")
args = parser.parse_args()

print args.files # ['file1.txt', 'file2.py']

It's in the first example in the docs, but somehow I managed to miss it.

Nargs='*' means that any number of arguments will be read. If you use nargs='+' the script will bitch if doesn't get at least one argument. Nargs also takes integers like this: nargs=2.

Another example:
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("first_arg",nargs=1)
parser.add_argument("items",nargs="+")
args = parser.parse_args()

print "First argument: %s" % args.first_arg
print "The rest: %s" % args.items
Gives:
$ python example2.py Hello there world
First argument: ['Hello']
The rest: ['there', 'world']
$ python example2.py Hi
usage: example2.py [-h] first_arg items [items ...]
example2.py: error: too few arguments

Follow me on Twitter
I'm building monitoring tool for site speed and Core Web Vitals.
➔ Start monitoring your website or run a free site speed test