python“help”功能:打印docstrings

问题描述 投票:14回答:4

是否有打印输出帮助('myfun')的选项。我看到的行为是输出打印到std.out并且脚本等待用户输入(即输入'q'继续)。

必须有一个设置来设置它只是转储文档字符串。

或者,如果我可以转储文档字符串PLUS“def f(args):”行也可以。

搜索“python帮助功能”是滑稽的。 :)也许我错过了一些不错的pydoc页面那里解释了一切?

python docstring
4个回答
17
投票

要获得由help(str)打印到变量strhelp的帮助:

import pydoc
strhelp = pydoc.render_doc(str, "Help on %s")

当然,您可以轻松打印它而无需分页等。


4
投票

你已经看到了docstring的引用,这是一个神奇的__doc__变量,它包含了帮助的主体:

def foo(a,b,c): 
   ''' DOES NOTHING!!!! '''
   pass

print foo.__doc__ # DOES NOTHING!!!!

要获取函数的名称,只需使用__name__

def foo(a,b,c): pass

print foo.__name__ # foo

获取未构建的函数签名的方法可以使用func_code属性,从中可以读取其co_varnames:

def foo(a,b,c): pass
print foo.func_code.co_varnames # ('a', 'b', 'c')

我还没有找到如何为内置函数做同样的事情。


4
投票

如果要从代码访问原始文档字符串:

   myvar = obj.__doc__
   print(obj.__doc__)

帮助函数执行一些额外的处理,接受的答案显示了如何使用pydoc.render_doc()复制它。


2
投票
>>> x = 2
>>> x.__doc__
'int(x[, base]) -> integer\n\nConvert a string or number to an integer, if possi
ble.  A floating point\nargument will be truncated towards zero (this does not i
nclude a string\nrepresentation of a floating point number!)  When converting a
string, use\nthe optional base.  It is an error to supply a base when converting
 a\nnon-string. If the argument is outside the integer range a long object\nwill
 be returned instead.'

那是你需要的吗?

编辑 - 你可以print(x.__doc__)和关于函数签名,你可以使用inspect模块构建它。

>>> inspect.formatargspec(inspect.getargspec(os.path.join))
'((a,), p, None, None)'
>>> help(os.path.join)
Help on function join in module ntpath:

join(a, *p)
    Join two or more pathname components, inserting "\" as needed
© www.soinside.com 2019 - 2024. All rights reserved.