gpt4 book ai didi

Python 选项解析

转载 作者:行者123 更新时间:2023-11-28 22:04:17 25 4
gpt4 key购买 nike

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

非常感谢任何帮助!

最佳答案

该错误是因为 opts.Input_PathNone,而不是您的路径字符串/unicode。

你确定你调用的脚本正确吗?在任何情况下,您都应该添加一些错误检查代码,以确保如果用户没有输入-p,程序不会崩溃。

或者,将其更改为位置参数,使其成为 optparse 的“必需”: http://docs.python.org/library/optparse.html#what-are-positional-arguments-for

编辑:optparse 也已弃用,对于您可能想要使用的新项目 argparse .

关于Python 选项解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7504213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com