【问题标题】:Python OptParserPython OptParse
【发布时间】:2011-11-22 04:24:54
【问题描述】:

我正在尝试在 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)

错误:-

回溯(最近一次通话最后): 文件“/Users/armed/Documents/Python_Test.py”,第 8 行,在 打印 os.path.isdir(opts.Input_Path) 文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py”,第 41 行,在 isdir st = os.stat(s) TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 NoneType

非常感谢任何帮助!

【问题讨论】:

  • 你确定用“-p something”调用你的脚本吗?
  • 是的,我是。我将它作为字符串输入,但我认为它被存储为一个列表,因为当我在 opts.Input_Path 中执行文件并打印文件时,它会为我输入的任何内容逐个字母地显示输出。你知道这是为什么吗?我只想让它打印路径指向的目录中的文件
  • 字符串是一个可迭代的对象,就像一个列表。 "for a in a_string" 将遍历字符串的字符。而不是 for 循环,只需使用属性 opts.Input_Path 本身。
  • 这里是 optparse 已被argparse 弃用的强制性评论。

标签: python


【解决方案1】:

该错误是因为opts.Input_PathNone,而不是您的路径字符串/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

【讨论】:

  • 非常感谢!这真的很有帮助。 :)
猜你喜欢
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
相关资源
最近更新 更多