3

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?

noumenal
  • 1,077
  • 2
  • 16
  • 36

3 Answers3

2

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"
Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
1

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)"
noumenal
  • 1,077
  • 2
  • 16
  • 36
  • This answer strikes me as very dangerous, since all of these options execute the full script — which could have unpredictable consequences including the permanent loss of data. (What if the script ignores its options and is a cleanup script that deletes files, for example.) Also: the `-c` trick won’t work if the script takes a `-c` option; and what of `-c` means “clean” and deletes files; and, it won’t print the docstring, it would print the `argparse` documentation, which are often quite different things. – Brandon Rhodes Jan 08 '21 at 12:57
0

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.

renefritze
  • 2,167
  • 14
  • 25