Getting doc line of python file

Is there a way to get the doc string of a python file if I only have the file name? For example, I have a python file called a.py. I know that it has a document line (which was previously set), but does not know its internal structure if it has any classes or main, etc.? I hope I do not forget something pretty obvious. If I know that I have a main function, I can do this using import

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

I can’t just like that:

  filename.__doc__ #it does not work 
+4
source share
3 answers

You have to do ...

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

or even easier ...

 import a mydocstring = a.__doc__ 
+4
source
 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) 
+2
source

And if you need the docks from the module, you are already:

 import sys sys.modules[__name__].__doc__ 
0
source

All Articles