Python print help to file

How to print module documentation in Python

I know this question is very simple, I know it must have been asked a lot of times and I did my search on both SO and Google but I could not find the answer, probably due to my lack of ability of putting what I seek into a proper sentence. I want to be able to read the docs of what I import. For example if I import x by «import x», I want to run this command, and have its docs printed in Python or ipython. What is this command-function? Thank you. PS. I don’t mean dir(), I mean the function that will actually print the docs for me to see and read what functionalities etc. this module x has.

3 Answers 3

You can use the .__doc__ attribute of the module of function:

In [14]: import itertools In [15]: print itertools.__doc__ Functional tools for creating and using iterators. In [18]: print itertools.permutations.__doc__ permutations(iterable[, r]) --> permutations object Return successive r-length permutations of elements in the iterable. permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1) 

Both of help() and __doc__ work fine on both inbuilt and on our own modules:

def myfunc(): """ this is some info on myfunc """ foo=2 bar=3 In [4]: help(so27.myfunc) In [5]: import foo In [6]: print foo.myfunc.__doc__ this is some info on func In [7]: help(foo.myfunc) Help on function myfunc in module foo: myfunc() this is some info on func 

Источник

Читайте также:  Coding forums showthread php

Как сделать документацию к функции?

Документировать функции очень важно. Это помогает не только узнать что делает функция, но и подсказывает какие именованые аргументы она принимает и что в следствии может возвращать. Документировать функции очень просто. Просто и обращаться к документации каждой функции.

Чтобы создать описание функции, внутри функции перед её телом нужно сделать многострочный комментарий(делается он с помощью трёх знаков »’ ). Этот комментарий будет рассматриваться, как аттрибут .__doc__ и будет появляться при вызове help() , но об этом чуть позже.

Давайте сделаем небольшую функцию:

def to_str_smth(smth, step=1): smth = str(smth) return smth[::step] 

Функция есть, давайте сделаем к ней описание для тех, кто будет, например, импортировать модуль с ней.

def to_str_smth(smth, step=1): """ to_str_smth(smth, step=1) Makes the input data string and return it sliced with step """ smth = str(smth) return smth[::step] 

Теперь вызовем нашу документацию:

Документацию можно вызвать и с помощью команды help(), но тогда свернётся весь наш аутпут и откроется что-то типа подокна (если вы знакомы с редактором nano, то вам будет проще понять), из которого можно выйти, нажав q

Почему не вызывем документацию у to_str_smth(), указывая скобки? Потому что так функция затребует аргументы, если они обязательны. К тому же, таким образом мы можем вернуть документацию подфункции, если она указана в return.

Посмотрим, например, на эту функцию:

def plus(a, b): """ plus(a, b) Return a + b, typed float """ return float(a + b) 

Давайте попробуем вывести на экран документацию для неё, указав скобки:

Как мы видим, функция запросила аргументы. Теперь давайте попробуем их передать и снова вызывать документацию:

Не совсем то, что хотелось бы видеть.

Важно соблюдать одинаковое форматирование при написании документации, как и при написании кода. Ознакомиться с рекомендациями по тому, как стоит документировать функции и классы, можно в справке PEP257. Кстати, всё, что заключённо между парой »’ игнорируется интерпретатором и таким образом можно спрятать блоки кода при его тестах.

Если мы хотим сохранить документацию, сделать это можно с помощью программы, которая идёт в комплекте с Python под названием pydoc. Для каждой версии есть свой pydoc, так что убедитесь, что вы запускаете ту версию pydoc’а, иначе может возникнуть конфликт импорта модулей.

Сделать это можно следующим образом (подразумевается, что запуск идёт из директории с модулем):

pydoc3.6 -w ./mymodule # также подойдёт pydoc -w ./mymodule.py 

Таким образом будет создан html файл с вашей документацией для модуля mymodule. Дизайн не очень, зато быстро. Для стартапов пойдёт. К тому же, помимо pydoc есть множество программ, которые генерируют документацию в файл. Вот некоторые из них:

Обращаясь к документации с помощью help() или .__doc__ , мы можем разрешить множество вопросов, связанных с импортируемыми модулями, а документируя свой код — не забыть что он делает, возвращает и для чего он нужен спустя долгое время.

Источник

Python > Save help() output to formated html file?

I have a very long output from help() function and found it a bit hard to find what I am looking for in the script editor. Is it possible to save the help() output as a formatted html file?

there are other options outside the answers below, you can check this: python documentation generator for more. I made a quick test with sphinx, but I find it to convoluted to my taste so I cannot get nothing out of it

3 Answers 3

Yes, you can use the pydoc module to do this in the Python interpreter:

import pydoc pydoc.writedoc("sys") 

This code will write the documentation for the sys module to a file sys.html in the current directory. If you want to get documentation for a package, you need to use pydoc.writedocs() instead.

The Python docs say that you can also run pydoc -w from the command line, but this didn’t work for me without including the full path:

C:\Python27\Lib\pydoc.py -w sys 

to run pydoc or any other module from anywhere as a script you need to do python -m [arguments] in this case that is python -m pydoc -w sys

another option that may be worth mentioning is: redirect the standard output to a file, but this will give you a text file instead of a html

import sys with open("range help.txt","w") as archi: t = sys.stdout sys.stdout = archi help(range) sys.stdout = t 

Copperfield, your code worked beautifully. I didn’t know how to paste code in this comment section, so I just posted as an answer. Thanks!!

Thank you so much for your help! Ok, I put together what I have learned from all of you so far. This prints everything in my package to a text file. Making it much easier to read and search. I know this is a bit of a hack. So please feel free to improve it. Thanks again!!

import sys, os.path, pkgutil, webbrowser pkgpath ="C:/Users/Haggai/Documents/maya/scripts/mypackage" my_modules = [name for _, name, _ in pkgutil.walk_packages([pkgpath])] out_file = 'C:/Users/Haggai/Desktop/History.txt' with open(out_file,"w") as archi: t = sys.stdout sys.stdout = archi for i in my_modules: help(i) sys.stdout = t webbrowser.open('file://' + out_file) 

Thank you so much for pointing that out Copperfield, This worked.

tmp_list = dir(oSel) content = '\n'.join(lines) with open('C:/Users/Haggai/Desktop/dir.txt',"w") as text_file: text_file.write(content ) 

Источник

Is there an option to print the output of help()?

Is there an option to print the output of help(‘myfun’). The behaviour I’m seeing is that output is printed to std.out and the script waits for user input (i.e. type ‘q’ to continue). There must be a setting to set this to just dump docstrings. Alternatively, if I could just dump the docstring PLUS the «def f(args):» line that would be fine too. Searching for «python help function» is comical. 🙂 Maybe I’m missing some nice pydoc page somewhere out there that explains it all?

4 Answers 4

To get exactly the help that’s printed by help(str) into the variable strhelp :

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

Of course you can then easily print it without paging, etc.

Ha . I guess it’s as testament to the stackoverflow interface helping me with my scattered work life! I was perusing my profile, actually paid attention to my list of questions and noticed a few that I had forgotten to accept.

If you want to access the raw docstring from code:

 myvar = obj.__doc__ print(obj.__doc__) 

The help function does some additional processing, the accepted answer shows how to replicate this with pydoc.render_doc().

For some reason that I yet ignore, this is generally different from the result of pydoc.render_doc(obj) —I guess notably in the case of a function defined inside another function, that sets its docstring by setting func.__doc__ = … .

You’ve already seen reference to the docstring, the magic __doc__ variable which holds the body of the help:

def foo(a,b,c): ''' DOES NOTHING. ''' pass print foo.__doc__ # DOES NOTHING. 

To get the name of a function, you just use __name__ :

def foo(a,b,c): pass print foo.__name__ # foo 

The way to get the signature of a function which is not built in you can use the func_code property and from that you can read its co_varnames:

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

I’ve not found out how to do the same for built in functions.

co_varnames will show a lot more than just the input params: def foo(a,b,c): d = «foo» e = «bar» print foo.func_code.co_varnames (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)

>>> 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.' 

edit — you can print(x.__doc__) and concerning the function signature, you can build it using the inspect module.

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

Источник

Оцените статью