Octaviour
Octaviour

Reputation: 805

Obtain Python docstring of arbitrary script file

I am writing a module that requires the docstring of the calling script. Thus far I have managed to obtain the filename of the calling script using

import inspect
filename = inspect.stack()[1].filename

The docstring can be found inside the calling script using __doc__. Getting the docstring from the called script does not seem trivial however. Of course I could write a function, but this is bound to ignore some uncommon cases. I there a way to actually parse the calling script to find its docstring (without executing its code)?

Upvotes: 5

Views: 2004

Answers (1)

Octaviour
Octaviour

Reputation: 805

Based on chaos's suggestion to use ast I wrote the following which seems to work nicely.

import ast

with open(fname, 'r') as f:
    tree = ast.parse(f.read())
docstring = ast.get_docstring(tree)

Upvotes: 7

Related Questions