Python OptParser使用方法

2 投票
2 回答
1630 浏览
提问于 2025-04-17 02:47

我正在尝试在Python中使用optparser输入一个路径。不幸的是,这段代码总是出现错误。

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)

错误信息:

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

任何帮助都非常感谢!

2 个回答

3

这个错误是因为 opts.Input_Path 的值是 None,也就是说它没有被正确设置成你的路径字符串或Unicode字符。

你确定你是正确调用这个脚本的吗?无论如何,你应该加一些错误检查的代码,这样如果用户没有输入 -p,程序就不会直接崩溃。

或者,你可以把它改成一个位置参数,这样就可以让它变成“必填项”,使用 optparse 的话可以参考这个链接:http://docs.python.org/library/optparse.html#what-are-positional-arguments-for

补充:另外 optparse 已经不再推荐使用了,如果是新项目的话,你可能想用 argparse

2

我复制了你的脚本并运行了一下。看起来你调用脚本的方式不对:

 $ 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

但是

$ python test.py --path /tmp
True

撰写回答