我正在尝试学习如何使用Python-click。我无法将帮助参数与我的选项之一一起使用,因此我最终放弃并更改了代码以不包含该选项的帮助。然而,尽管关闭并重新启动 Python 并且现在重新启动我的计算机,与尝试使用帮助参数相关的错误消息仍然出现。
代码:
import click
def something():
pass
@click.command()
@click.argument('dest_dir',type=click.Path(exists=True, readable=True,
resolve_path=True, dir_okay=True),
help='Location of directory where results will be saved')
@click.option('--use_terms', is_flag=True,
help='Process strings based on terms or phrases')
@click.option('--use_query', is_flag=True, help='Process string based on
search query')
@click.option('--search_phrase', '-s', multiple=True)
def do_process(dest_dir,use_terms,use_query,*search_phrase):
""" testing setting parameters for snip tables"""
outref = open('e:\\myTemp\\testq.txt')
ms = dest_dir + '\n'
if use_terms:
ms += use_term + '\n'
else:
ms += use_query + '\n'
for each in search_phrase:
x = something()
ms += each + '\n'
outref.writelines(ms)
outref.close()
if __name__ == "__main__":
do_process()
最初是为了我最后的@click.option
@click.option('--search_phrase', '-s', multiple=True, help='The search phrase to use')
我不断收到一条无法解决的错误消息,该消息与未知参数帮助有关。我放弃了它,改为上面的内容,现在我遇到了类似的错误,
然后我关闭了 Python,关闭了模块,然后重新启动了 Python,打开并再次运行了我的代码,但仍然收到此错误消息
回溯:
Traceback (most recent call last):
File "C:\Program Files\PYTHON\snipTables\test_snip_click.py", line 14, in <module>
@click.option('--search_phrase', '-s', multiple=True)
File "C:\Program Files\PYTHON\lib\site-packages\click\decorators.py", line 148, in decorator
_param_memo(f, ArgumentClass(param_decls, **attrs))
File "C:\Program Files\PYTHON\lib\site-packages\click\core.py", line 1618, in __init__
Parameter.__init__(self, param_decls, required=required, **attrs)
TypeError: __init__() got an unexpected keyword argument 'help'
然后我关闭了Python Idle,我保存并关闭了我的代码,然后重新启动了Python,重新打开了我的代码,但我仍然得到相同的回溯,除了注意到回溯具有我在击败我的代码后切换到的代码行努力对着显示器并放弃
我正准备重新启动,但我真的很好奇原因。
我重新启动后仍然遇到相同的错误
重命名文件并再次运行没有改变结果 - 相同的回溯
最佳答案
问题是 click 不接受带有参数的帮助字符串。这是有趣的行为。与参数关联的帮助字符串将是处理参数和选项的函数中的字符串。
错误消息将始终显示与最后一个选项相关的信息。所以这个例子的正确代码是
import click
def something():
pass
@click.command()
@click.argument('dest_dir',type=click.Path(exists=True, readable=True,
resolve_path=True, dir_okay=True)
##Notice no help string here
@click.option('--use_terms', is_flag=True,
help='Process strings based on terms or phrases')
@click.option('--use_query', is_flag=True, help='Process string based on
search query')
@click.option('--search_phrase', '-s', multiple=True)
def do_process(dest_dir,use_terms,use_query,*search_phrase):
""" testing setting parameters for snip tables"""
outref = open('e:\\myTemp\\testq.txt')
ms = dest_dir + '\n'
if use_terms:
ms += use_term + '\n'
else:
ms += use_query + '\n'
for each in search_phrase:
x = something()
ms += each + '\n'
outref.writelines(ms)
outref.close()
if __name__ == "__main__":
do_process()
这运行得很好,我最初遇到的问题是 click 没有很好地解释错误的来源。上面,即使我删除了选项中的帮助字符串,单击解析器也会将参数中的帮助字符串与它解析的最后一个选项相关联。
关于Python 单击与选项关联的帮助字符串中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32150648/