如何为Python文件添加自动化头部注释

5 投票
3 回答
4215 浏览
提问于 2025-04-16 18:46

在Python中,正确的文件头格式可以在这里找到。

我想用VIM或者一个脚本,给文件的开头加上一些常见的信息,比如__author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ 和 __version__ 。如果能加上SVN的关键词就更好了。最重要的是能加到新文件上,给已有的文件加上这些信息算是额外的好处。

Ruslan的博客提供了Emacs的解决方案,但我找不到Python的解决办法。

有没有人能分享一下在不使用Emacs的情况下,如何在Python中做到这一点?VIM可以像这样从一个文件复制文本到另一个文件,但也许还有更好的方法。

3 个回答

0

你只需要去 http://www.vim.org 网站,在那里搜索“新文件模板”,你会找到很多可以解决这个问题的插件,看看这些插件,挑一个你喜欢的就行。

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()

基本上,我会读取模板文件,把里面的标签替换成实际的信息,然后把结果插入到新创建文件的开头。每当 vim 创建一个新文件时,就会调用 s:insert_description() 这个函数。这个设置是在最后一行的 autocmd 中完成的。

你可以根据这段代码,创建一个适用于 Python 的类似功能。

6

我非常推荐这个 snipMate 插件。你可以很方便地为不同类型的文件添加新的代码片段,只需要输入一个关键词,然后按下 tab 键就可以触发。例如,你只需按下

header<TAB>

就会自动添加所有需要的字段,你可以轻松地通过 tab 键在每个需要填写的地方切换。其实在内置的 Python 代码片段中,已经有一个叫做 docs 的片段,它可以自动填充类似文档字符串的元数据,你可以根据自己的需要进行修改。这里给你一个 snip 格式的例子:

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

动态条目可以通过在你的代码片段中使用反引号来支持(文件名和 g:snips_author 是上面可填入条目的默认值 1 和 2)。日期可以通过以下方式添加:

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

(来自 snipMate 帮助文档)。

撰写回答