2011-08-19 128 views
10

是否有打印幫助輸出('myfun')的選項。我看到的行爲是輸出打印到std.out並且腳本等待用戶輸入(即鍵入'q'繼續)。蟒蛇「幫助」功能:打印文檔

必須有一個設置來設置它只是轉儲docstrings。

另外,如果我可以只是轉儲文件字符串PLUS「def f(args):」行,那也可以。

搜索「python幫助函數」是滑稽的。 :)也許我錯過了一些不錯的pydoc頁面,它解釋了這一切?

回答

13

要得到完全多數民衆贊成由help(str)印入變量strhelp幫助:

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

當然你也可以那麼輕鬆地打印無分頁等

+0

其他答案可能是正確的,但這正是我所需要的。 – mathtick

+0

@mathtick:現在這就是我所說的認真,在這麼久之後接受一個答案! – kindall

+0

哈...我想這是對stackoverflow界面的幫助,幫助我分散工作生活!我正在細讀我的個人資料,實際上關注了我的問題列表,並注意到我忘記接受的一些內容。 – mathtick

1
>>> 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 
3

只是

print obj.__doc__ 

myvar = obj.__doc__ 

幫助功能存在以交互方式查看幫助,它可以很容易地獲取足夠離不開它。

+0

出於某種原因,我還忽略了,這通常與'pydoc.render_doc(obj)'的結果不同 - 我想知道在另一個函數內定義函數的情況下,通過設置func .__ doc__ = ...來設置它的文檔字符串。 – EOL

2

您已經看到了參考文檔字符串,魔術__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') 

我還沒有找到如何做相同的內置函數。