我想抓住命令行應用程序中的文檔字符串,但每次我調用內置的help()函數時,Python都會進入交互模式。Python獲取文檔字符串而不進入交互模式
如何獲取對象的文檔字符串和而不是是否擁有Python抓取焦點?
我想抓住命令行應用程序中的文檔字符串,但每次我調用內置的help()函數時,Python都會進入交互模式。Python獲取文檔字符串而不進入交互模式
如何獲取對象的文檔字符串和而不是是否擁有Python抓取焦點?
任何文檔字符串可以通過.__doc__
屬性:
>>> print str.__doc__
在Python 3,你需要括號打印:
>>> print(str.__doc__)
您可以使用dir(
{插入類的名字在這裏} )
獲取一個類的內容,然後遍歷它,尋找方法或其他東西。這個例子看起來一類Task
啓動名爲cmd
方法,並得到他們的文檔字符串:
command_help = dict()
for key in dir(Task):
if key.startswith('cmd'):
command_help[ key ] = getattr(Task, key).__doc__
.__doc__
是最好的選擇。但是,您也可以使用inspect.getdoc
獲取docstring
。使用它的一個優點是,它可以從縮排排列代碼塊的文檔字符串中刪除縮進。
實施例:
In [21]: def foo():
....: """
....: This is the most useful docstring.
....: """
....: pass
....:
In [22]: from inspect import getdoc
In [23]: print(getdoc(foo))
This is the most useful docstring.
In [24]: print(getdoc(str))
str(object='') -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.