Asad wrote:

> Hi All ,
> 
>           I tried the following code  :
> 
> parser = argparse.ArgumentParser()
> parser.add_argument("first")
> parser.add_argument("second", nargs="?")
> args = parser.parse_args()
> print("first:", args.first)
> 
> print("second:", args.second)
> 
> When I execute the script it gives error :
> 
> python python_json_20001_oratest_v1.py "file1"
> ('first:', 'file1')
> ('second:', None)
> Traceback (most recent call last):
>   File "test.py", line 211, in <module>
>     with open(args.second, 'r') as f :
> TypeError: coercing to Unicode: need string or buffer, NoneType found
> 
> 
> if I see in line number 211 it with open(args.second, 'r') as f :
> 
> try :
>         with open(args.second, 'r') as f :
>              for line in f:
>                 print line
> except IOError:
>          print "The default error is err-1 because file2 was not provided
>          "

How do you know that the file was not provided? The name might have been 
misspelt or the user lacks the permission to read it.

> Does that mean my try and except block is not working because if
> args.second  is None as in this case then it should print "The default
> error is err-1 because file2 was not provided "
> 
> Please advice ,

If you just want to terminate the script with a helpful message you should 
make the second argument mandatory, too:

parser = argparse.ArgumentParser()
parser.add_argument("first")
parser.add_argument("second")
args = parser.parse_args()

That way the parse_args() call will terminate the script and the user will 
see an error message immediately.

If for some reason you want to keep the argument optional you can check for 
None before trying to open the file:

if args.second is not None:
    try:
        with open(args.second, 'r') as f :
            for line in f:
                print line
    except IOError as err:
        print err  # print actually what happened, not what you guess
else:
    print "File 'second' was not provided on the command line"



_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to