根据内部注释记录和详细说明单个脚本 [英] Documenting and detailing a single script based on the comments inside

查看:80
本文介绍了根据内部注释记录和详细说明单个脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要编写一组脚本,每个脚本彼此独立,但有一些相似之处。所有脚本的结构都可能相同,并且可能看起来像这样:

 #-*-编码:utf-8-*-

小描述和信息
@author:作者


#导入
导入numpy为np
导入数学
从scipy导入信号
...

#常量定义(总是大写字母可变)
CONSTANT_1 = 5
CONSTANT_2 = 10

#主类
类Test():
def __init __(self ,run_id,参数):
#一些不太重要的东西

def _run(self,parameters):
#主程序返回结果对象。

对于每个脚本,我想编写文档并将其导出为PDF。我需要一个库/模块/解析器来读取脚本,提取注释的注释,代码,然后将其重新组合成所需的输出格式。


例如,在 _run()方法,注释中可能包含一些详细步骤:

  def _run(self,parameters ):
#步骤1:我们首先通过执行此
代码来完成它

#步骤2:然后我们执行此
代码来完成它
代码
代码#该代码可以执行

我可以使用哪个库/解析器来分析python脚本并输出PDF?
起初,我想到的是 sphinx ,但它不适合我的需要,因为我必须设计一个自定义扩展名。此外, sphinx 的优势在于相同或不同模块的多个脚本之间的链接和层次结构。就我而言,我只会记录一个脚本,一次只记录一个文件。


然后,我的第二个想法是使用 RST 格式和 RST2PDF 创建PDF。对于解析器,我可以设计一个解析器,该解析器读取 .py 文件并提取注释/修饰的行或下面建议的行,然后编写 RST 文件。

 #-说明
##事物的标题
#在此处执行
#-

#代码
提取一些代码并将其放入文档
更多代码
#-
.py
文件内容的SHA1哈希,并将其作为PDF文档中的参考。

解决方案

文档字符串而不是注释


为了使事情更轻松,您可能想利用文档字符串,而不是注释:


文档字符串是一个字符串文字,它作为模块,函数,类或方法定义中的第一条语句出现。这样的文档字符串成为该对象的 __ doc __ 特殊属性。


这样,您可以生成文档时在解​​析脚本时使用 __ doc __ 属性。


函数/模块定义后紧跟的三个双引号字符串成为文档字符串只是语法加糖。您可以根据需要以编程方式编辑 __ doc __ 属性。


例如,您可以使用装饰器,以使在特定情况下更好地创建文档字符串。例如,让您内联注释步骤,但仍将注释添加到docstring(在浏览器中编程,可能会出现错误):

  def with_steps(func):
def add_step(n,doc):
func .__ doc__ = func .__ doc__ + n步%d:%s %(n,doc)
func.add_step = add_step

@with_steps
def _run(self,parameters):
的初始说明转换为初始文档字符串
_run.add_step(1,我们首先开始执行此操作)
代码来执行此操作

_run.add_step(2,然后执行此操作))
代码做到这一点
代码

这会创建一个这样的文档字符串:


将初始描述转换为初始文档字符串

步骤1:首先,这样做

步骤2:然后我们开始


您就会明白。


从文档脚本生成PDF


Sphinx

我个人将通过捆绑的 LaTeXBuilder 或使用 rinoh 如果您不想依赖LaTeX。


但是,您必须使用Sphinx可以理解的文档字符串格式,例如reStructuredText或Google样式文档字符串。


AST

另一种方法是使用 ast 来提取文档字符串。这可能是Sphinx autodoc扩展在内部使用的从源文件中提取文档的方式。这里有一些有关如何执行此操作的示例,例如此要旨此博客文章


这样,您可以编写一个脚本来解析和输出所需的任何格式。例如,您可以使用 pandoc 输出Markdown或reST并将其转换为PDF。


您可以直接在文档字符串中编写标记文本,这将给您带来很大的灵活性。假设您想使用markdown编写文档–只需直接在文档字符串中编写markdown。

  def _run(self,parameters):
示例脚本
================

此脚本执行a,b,c

1.首先执行
2.接下来执行其他操作
3.返回其他内容

用法示例:

result = script(参数)
foo = [r.foo表示结果中的r]

可以使用ast提取此字符串,并使用您认为合适的任何库对其进行解析/处理。


I am going to write a set of scripts, each independent from the others but with some similarities. The structure will most likely be the same for all the scripts and probably looks like:

# -*- coding: utf-8 -*-
"""
Small description and information
@author: Author
"""

# Imports
import numpy as np
import math
from scipy import signal
...

# Constant definition (always with variable in capital letters)
CONSTANT_1 = 5
CONSTANT_2 = 10

# Main class
class Test():
    def __init__(self, run_id, parameters):
        # Some stuff not too important
        
    def _run(self, parameters):
        # Main program returning a result object. 

For each script, I would like to write documentation and export it in PDF. I need a library/module/parser which reads the scripts, extracts the noted comment, code and puts it back together in the desired output format.

For instance, in the _run() method, there might be several steps detailed in the comments:

def _run(self, parameters):
        # Step 1: we start by doing this
        code to do it
            
        # Step 2: then we do this
        code to do it
        code 
        code # this code does that

Which library/parser could I use to analyze the python script and output a PDF? At first, I was thinking of sphinx, but it is not suited to my need as I would have to design a custom extension. Moreover, sphinx strength lies in the links and hierarchy between multiple scripts of a same or of different modules. In my case, I will only be documenting one script, one file at a time.

Then, my second idea is to use the RST format and RST2PDF to create the PDF. For the parser, I could then design a parser which reads the .py file and extract the commented/decorated lines or set of lines as proposed below, and then write the RST file.

#-description
## Title of something
# doing this here
#-

#-code
some code to extract and put in the doc
some more code
#-

Finally, I would also like to be able to execute some code and catch the result in order to put it in the output PDF file. For instance, I could run a python code to compute the SHA1 hash of the .py file content and include this as a reference in the PDF documentation.

解决方案

Docstrings instead of comments

In order to make things easier for yourself, you probably want to make use of docstrings rather than comments:

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

This way, you can make use of the __doc__ attribute when parsing the scripts when generating documentation.

The three double quoted string placed immediately after the function/module definition that becomes the docstring is just syntactic sugaring. You can edit the __doc__ attribute programmatically as needed.

For instance, you can make use of decorators to make the creation of docstrings nicer in your specific case. For instance, to let you comment the steps inline, but still adding the comments to the docstring (programmed in browser, probably with errors):

def with_steps(func):
  def add_step(n, doc):
    func.__doc__ = func.__doc__ + "\nStep %d: %s" % (n, doc)
  func.add_step = add_step

@with_steps
def _run(self, parameters):
  """Initial description that is turned into the initial docstring"""
  _run.add_step(1, "we start by doing this")
  code to do it
        
  _run.add_step(2, "then we do this")
  code to do it
  code 

Which would create a docstring like this:

Initial description that is turned into the initial docstring
Step 1: we start by doing this
Step 2: then we do this

You get the idea.

Generating PDF from documented scripts

Sphinx

Personally, I'd just try the PDF-builders available for Sphinx, via the bundled LaTeXBuilder or using rinoh if you don't want to depend on LaTeX.

However, you would have to use a docstring format that Sphinx understands, such as reStructuredText or Google Style Docstrings.

AST

An alternative is to use ast to extract the docstrings. This is probably what the Sphinx autodoc extension uses internally to extract the documentation from the source files. There are a few examples out there on how to do this, like this gist or this blog post.

This way you can write a script that parses and outputs any formats you want. For instance, you can output Markdown or reST and convert it to PDF using pandoc.

You could write marked up text directly in the docstrings, which would give you a lot of flexibility. Let's say you wanted to write your documentation using markdown – just write markdown directly in your docstring.

def _run(self, parameters):
  """Example script
  ================

  This script does a, b, c

  1. Does something first
  2. Does something else next
  3. Returns something else

  Usage example:
  
      result = script(parameters)
      foo = [r.foo for r in results]
  """

This string can be extracted using ast and parsed/processed using whatever library you see fit.

这篇关于根据内部注释记录和详细说明单个脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆