![](/img/trans.png)
[英]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.