Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 730
noumenal Avatar asked May 01 '26 19:05

noumenal


2 Answers

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"
like image 114
Brandon Rhodes Avatar answered May 03 '26 09:05

Brandon Rhodes


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)"
like image 22
noumenal Avatar answered May 03 '26 08:05

noumenal