【发布时间】:2017-04-18 19:17:33
【问题描述】:
我在 python3.5 中使用Argparse。我需要的参数之一是一个长字符串,它可以包含任何字符,如单引号或双引号。我不想限制用户如何使用这个 python 脚本并强迫他删除这个字符。所以我正在寻找一种解决方案来处理我的代码中的引号。
这是我的参数解析器:
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('Error: %s\n' % message)
self.print_help()
sys.exit(2)
def msg(name=None):
return '''python3.5 file.py Text'''
parser = MyParser(description='You must pass exactly one arguments after classifier.py . Use quotes after and before the argument.', usage=MyParser.msg())
parser.add_argument('text', help='"News Text" for classification (Required Parameter)')
args = parser.parse_args()
这种类型的参数失败并出现无法识别的错误:
>>> python3.5 file.py "Apps infected by Gooligan include "Perfect Cleaner," and more."
Error: unrecognized arguments: Cleaner, and more.
而且有时没有任何错误:
>>> python3.5 file.py "Now "Support is expensive, and, when you're Google or any other vendor," said Michael Jude."
>
我想知道第二类错误的原因以及在我的代码中处理错误的解决方案,而无需注意参数。
【问题讨论】:
标签: python parameter-passing python-3.5 argparse