如何为Python文件添加自动化标题

5

Python的正确标题格式在这里有描述。

我想使用VIM或shell脚本,将常规元数据(如__author__、__authors__、__contact__、__copyright__、__license__、__deprecated__、__date__和__version__)添加到文件头部。希望能够添加SVN关键字。最重要的是将其添加到新文件中。将其添加到现有文件中则是额外加分。

Ruslan's Blog提供了Emacs的解决方案。但我无法找到Python的解决方案。

除了Emacs之外,还有哪些地方已经为Python实现了此功能?可以像这样从一个文件复制文本到另一个文件,但也许有更好的方法。


文件的创建和编辑日期、作者和版本信息都由源代码控制维护。我不理解为什么要在文件本身中添加冗余(可能不准确或过时)的信息。将版权/许可证信息放入LICENSE文件中,并将其从源代码中删除。它在那里没有任何作用。项目版本信息应该在项目的某个地方存在一次,而不是在每个文件的头部。联系信息应该放在README中。简而言之,这些标签都不属于源代码的顶部。 - Jonathan Hartley
3个回答

6
我强烈推荐使用snipMate插件。你可以轻松地按文件类型添加新的代码片段,并且只需要输入关键词并按下tab键就能触发它们,因此你可以快速地完成编码。
header<TAB>

所有字段都将被添加,您可以轻松地在每个需要按文件填写的字段之间切换。甚至已经有一个名为docs的代码片段在内置的python代码片段(vimfiles/snippets/python.snippets)中,它看起来填写了类似于文档字符串的元数据,您可以轻松地修改它以适应您的目的,以下是一个示例:

# Module Docstring
snippet docs
    '''
    File: ${1:`Filename('$1.py', 'foo.py')`}
    Author: ${2:`g:snips_author`}
    Description: ${3}
    '''

使用 snip 中的反引号,支持动态条目(文件名和 g:snips_author 作为上面可制表条目 1 和 2 的默认值)。日期可以通过以下方式添加:

`system("date +%Y-%m-%d")`

(来自snipMate帮助文档)

snipMate的有趣用途。我真的需要学会理解snipMate。 - john2x

5

这是我的C++文件模板:

/*****************************************************************************
 * @file <file_name>
 *
 * @date <date>
 * @author John Doe
 * @email jdoe@yourcompany.com
 *
 * @brief
 *
 * @detail
 *
 *****************************************************************************/

这是我在~/.vimrc文件中的内容:

" Reads the template file replacing the tags by the actual
" information and insert the result at the beginning of the buffer. At
" the end, creates two blank lines at the end of the file and
" position the cursor at the first one.
function! s:insert_description()
    let template = $HOME . "/.vim/template/cpp.template"
    let file_name = expand("%:t") " Get file name without path
    let date = strftime("%Y") " Get the current year in format YYYY
    let i = 0
    for line in readfile(template)
        let line = substitute(line, "<file_name>", file_name, "ge")
        let line = substitute(line, "<date>", date, "ge")
        call append(i, line)
        let i += 1
    endfor
    execute "normal! Go\<Esc>k"
endfunction
autocmd BufNewFile *.{c++,cpp,cc,c,h,hpp} call <SID>insert_description()

基本上,我会读取模板文件,将标签<description><author>替换为实际信息,并将结果插入到新创建的文件开头。函数s:insert_description()在vim创建新文件时被调用。这是由最后一行的autocmd设置的。
你可以以此代码为基础,创建相应的Python代码。

0

只需前往http://www.vim.org,搜索“新文件模板”,您将获得大量解决此类问题的插件,请查看并选择一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接