[英]Python Argparse - How can I add text to the default help message?
[英]How to override default help message on python function
我有一个带有许多参数和详细帮助信息的函数,例如:
def worker_function(arg1, arg2, arg3):
""" desired help message:
arg1 - blah
arg2 - foo
arg3 - bar
"""
print arg1, arg2, arg3
我也有一个包装函数,做一些会计,然后叫我worker_function,所有参数传递给它的 。
def wrapper_function(**args):
""" this function calls worker_function """
### do something here ...
worker_function(**args)
我希望包装函数的帮助消息(由python内置的help()函数显示)具有来自worker函数的参数列表和帮助消息。
我能得到的最接近的解决方案是:
wrapper_function.__doc__ += "\n\n" + worker_function.__doc__
这导致:
>>? help(wrapper_function)
Help on function wrapper_function in module __main__:
wrapper_function(**args)
this function calls worker function
desired help message:
arg1 - blah
arg2 - foo
arg3 - bar
但是这个描述缺少必要的部分 - 参数列表,即:
worker_function(arg1, arg2, arg3)
(在现实生活中,参数列表很长,告诉默认值,我希望自动显示)。
有没有办法在wrapper_function的帮助消息中添加参数列表或worker_function?
help()
使用inspect
模块在内部查找函数数据。 除非你默认覆盖函数元数据(如果可能的话),我认为你不能摆脱包装函数的定义。
但是,您可以使用包装函数中的信息填充包装函数的帮助文本。 您可以自己使用inspect
模块(尤其是getfullargspec
方法),也可以使用pydoc
模块(内部使用的help
)为您生成它。
import pydoc
def wrappedHelpText (wrappedFunc):
def decorator (f):
f.__doc__ = 'This method wraps the following method:\n\n' + pydoc.text.document(wrappedFunc)
return f
return decorator
@wrappedHelpText(worker_function)
def wrapper_function(**args):
worker_function(**args)
然后调用它的help
将生成更有用的输出,包括原始签名。
>>> help(wrapper_function)
Help on function wrapper_function in module __main__:
wrapper_function(**args)
This method wraps the following method:
worker_function(arg1, arg2, arg3)
desired help message:
arg1 - blah
arg2 - foo
arg3 - bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.