[Tutor] run with default value if input not given

Peter Otten __peter__ at web.de
Mon Oct 29 09:14:04 CET 2012

Saad Javed wrote:

> Hi,
> #!/usr/bin/env python
> import sys
> x = 'Saad is a boy'
> def main(x):
> a = []
> b = x.split(' ')
> for item in b:
> a.append(item)
> print a
> if __name__ == '__main__':
> x = sys.argv[1]
> main(x)
> How can I make this program run with the default value of x if I don't
> specify an argument at the command line?
> It should do this:
> saad at saad:~$ python test.py "Mariam is a girl"
> ['Mariam', 'is', 'a', 'girl']
> saad at saad:~$ python test.py
> ['Saad', 'is', 'a', 'boy']
> But the simply running "test.py" gives:
> Traceback (most recent call last):
>   File "input_test.py", line 13, in <module>
>     x = sys.argv[1]
> IndexError: list index out of range
> Saad

The argparse module (see <http://docs.python.org/2/library/argparse.html>)
offers a flexible way to specify command line arguments. Your program would 
look like this:

$ cat optional_arg.py
#!/usr/bin/env python
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Print a sentence as a list of words")
        "sentence", nargs="?",
        default="Mary had a little lamb")

    args = parser.parse_args()

    words = args.sentence.split()
    print words

if __name__ == "__main__":

...and work like this:

$ ./optional_arg.py
['Mary', 'had', 'a', 'little', 'lamb']
$ ./optional_arg.py "That's all folks"
["That's", 'all', 'folks']

It would include help...

$ ./optional_arg.py -h
usage: optional_arg.py [-h] [sentence]

Print a sentence as a list of words

positional arguments:

optional arguments:
  -h, --help  show this help message and exit

...and basic error reporting:

$ ./optional_arg.py That\'s all folks
usage: optional_arg.py [-h] [sentence]
optional_arg.py: error: unrecognized arguments: all folks

almost for free. So even if you find argparse too complex right now keep in 
mind that it exists until you are comfortable enough with Python to start 
making use of more parts of its standard library.

More information about the Tutor mailing list