6

Is there a way of getting the doc string of a python file if I have only the name of the file ? For instance I have a python file named a.py. I know that it has a doc string ( being mandated before) but don't know of its internal structure i.e if it has any classes or a main etc ? I hope I not forgetting something pretty obvious If I know it has a main function I can do it this way that is using import

     filename = 'a.py'
     foo = __import__(filename)
     filedescription = inspect.getdoc(foo.main())

I can't just do it this way:

     filename.__doc__    #it does not work
johnny alpaca
  • 75
  • 1
  • 4

3 Answers3

8
import ast

filepath = "/tmp/test.py"

file_contents = ""
with open(filepath) as fd:
    file_contents = fd.read()
module = ast.parse(file_contents)
docstring = ast.get_docstring(module)
if docstring is None:
    docstring = ""

print(docstring)
mengqi
  • 173
  • 2
  • 5
8

You should be doing...

foo = __import__('a')
mydocstring = foo.__doc__

or yet simpler...

import a
mydocstring = a.__doc__
Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
  • 1
    Aah got it Using import makes it an object and thus .__doc__ works otherwise a is just treated as a string and thus fails. – johnny alpaca Oct 21 '11 at 11:10
0

And if you need the docstrings of the module your are already in :

import sys
sys.modules[__name__].__doc__
Lucas B
  • 2,183
  • 1
  • 22
  • 22