Amritha
Amritha

Reputation: 815

Python OptParser

I am trying to input a path using optparser in python. Unfortunately this piece of code keeps showing an error.

import optparse,os

parser = optparse.OptionParser()
parser.add_option("-p","--path", help = "Prints path",dest = "Input_Path", metavar = "PATH")

(opts,args) =parser.parse_args()

print os.path.isdir(opts.Input_Path)

Error :-

Traceback (most recent call last):
  File "/Users/armed/Documents/Python_Test.py", line 8, in 
    print os.path.isdir(opts.Input_Path)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 41, in isdir
    st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, NoneType found

Any help is much appreciated !

Upvotes: 2

Views: 1633

Answers (2)

Dave
Dave

Reputation: 11899

That error is because opts.Input_Path is None, instead of being your path string/unicode.

Are you sure you are calling the script correctly? You should probably put in some error checking code in any case to make sure that if a user doesnt put -p, the program won't just crash.

Or, change it to a positional argument to make it 'required' by optparse: http://docs.python.org/library/optparse.html#what-are-positional-arguments-for

Edit: Also optparse is deprecated, for a new project you probably want to use argparse.

Upvotes: 3

culebrón
culebrón

Reputation: 36513

I copied your script and ran it. Looks like you call your script in a wrong way:

 $ python test.py /tmp
 Traceback (most recent call last):
   File "test.py", line 8, in <module>
     print os.path.isdir(opts.Input_Path)
   File "/usr/lib/python2.6/genericpath.py", line 41, in isdir
     st = os.stat(s)
 TypeError: coercing to Unicode: need string or buffer, NoneType found

but

$ python test.py --path /tmp
True

Upvotes: 2

Related Questions