noumenal
noumenal

Reputation: 1237

How can I read the docstring/help of a python module from cmd?

Consider that you are in the Windows command prompt or similar command line environment. How can you get info about a Python module from its docstring printed to the console?

Upvotes: 3

Views: 3572

Answers (3)

Brandon Rhodes
Brandon Rhodes

Reputation: 89517

Ideally you will want to load the module without executing it, which could have side effects. This is supported by Python’s ast module, which even has a helper for getting docstrings. Try this:

python3 -c"import ast, sys; a = ast.parse(open(sys.argv[1]).read()); print(ast.get_docstring(a))" "$1"

Upvotes: 2

renefritze
renefritze

Reputation: 2243

If you mean print interactively, just start python without any arguments to get a REPL (read–eval–print loop).

python
import mypackage
help(mypackage)
dir(mypackage)

executed one after another and so forth.

If you mean programmatically, see @noumenal's answer.

Upvotes: 0

noumenal
noumenal

Reputation: 1237

The Shortut (Hack)

Generally (in 2.7):

python -c"print 'Hello world'"

(in 3.x):

python -c"print('Hello world')"

will output: Hello world

But if you pass -c as an argument into a module, something else happens.

For an example, navigate to [your Python folder]\Tools\Scripts. If your script does not take parameter -c, a shortcut is simply to run:

python reindent.py -c

This will result in an error for the argument: "-c not recognized", but it will also return the docstring to the console. (One limitation is that the output cannot be routed to the clipboard using |clip.)

Generally, if your script myscript.py contains a docstring and expects no argument -c:

python myscript.py -c

returns

option -c not recognized
[__docstring__]

The Works

Once you are in the folder of reindent.py you can get an error-free docstring:

python -c"import reindent; print reindent.__doc__"

For producing a browsable help text, which prints both the docstring and lists the containing classes, functions, and global variables, use:

python -c"import reindent; help(reindent)"

To output to the clipboard only (Warning: Contents will be replaced!):

python -c"import reindent; help(reindent)"|clip

Deeper

Now that you have figured out what classes and functions are accessible (see above), you can retrieve the methods of a class and inner docstrings:

python -c"from reindent import Reindenter; help(Reindenter)"

Upvotes: 1

Related Questions