我想抓住命令行应用程序中的文档字符串,但每次我调用内置的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.