jeudi 26 janvier 2017

Error handling when expecting argument

First post, also first attempt to code something beyond 99 bottles...

I am working on code which accepts an argument from the cli such as a text file. Expected usage would be:

$:myfile.py input.txt

I've got that piece going smoothly however if an argument is not supplied, the cli returns an error and i'd like to provide some error response such as a help list or just a simple "Nope - give me a file"

Right now here is the first few lines:

import sys
with open(sys.argv[1], 'r') as f:
    ifile = f.read()
    if len(sys.argv) == 1:
        empty = "Please give me something to do!"
        print empty

If i supply the expected argument, everything is fine, but if no argument is supplied, I get this:

Traceback (most recent call last):
  File "myfile.py", line 3, in <module>
    with open(sys.argv[1], 'r') as f:
IndexError: list index out of range

Lets say I just want the variable "Empty" to print if the condition isn't met... what would i do to fix that.

Aucun commentaire:

Enregistrer un commentaire