整理一个完整的 VS Code Python 文件模板设置教程:

{
"Python File Header": {
"prefix": "header",
"body": [
"#!/usr/bin/env python",
"# -*- coding: utf-8 -*-",
"# @Time : $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE",
"# @Author : your_name",
"# @Email : your.email@example.com",
"# @File : $TM_FILENAME",
"# @Description : ${3:description}",
"",
"$0"
],
"description": "Add Python file header"
}
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : ${CURRENT_YEAR}/${CURRENT_MONTH}/${CURRENT_DATE} ${CURRENT_HOUR}:${CURRENT_MINUTE}
# @Author : ${USER}
# @Email : your.email@example.com
# @File : ${FILE_NAME}
# @Description :
常用的预定义变量:
对于已有的项目文件,可以使用 Python 脚本批量添加文件头:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import os
import fileinput
import shutil
from pathlib import Path
def generate_header(filename):
"""生成文件头信息"""
now = datetime.now()
header = [
"#!/usr/bin/env python",
"# -*- coding: utf-8 -*-",
f"# @Time : {now.year}/{now.month}/{now.day} {now.hour}:{now.minute}",
"# @Author : jcfszxc",
"# @Email : jcfszxc.ai@gmail.com",
f"# @File : {filename}",
"# @Description : ",
"\n"
]
return "\n".join(header)
def add_header_to_file(file_path):
"""给单个文件添加头部信息"""
# 创建临时文件
temp_file = file_path.parent / (file_path.name + '.tmp')
try:
with open(file_path, 'r', encoding='utf-8') as original, \
open(temp_file, 'w', encoding='utf-8') as temp:
# 检查文件是否已经有header
first_line = original.readline()
original.seek(0)
# 如果文件不是以shebang开头,则添加header
if not first_line.startswith('#!/usr/bin/env python'):
temp.write(generate_header(file_path.name))
# 写入原文件内容
for line in original:
temp.write(line)
# 替换原文件
shutil.move(str(temp_file), str(file_path))
print(f"成功添加header到: {file_path}")
except Exception as e:
print(f"处理文件 {file_path} 时出错: {str(e)}")
if temp_file.exists():
temp_file.unlink()
def process_directory(directory):
"""处理目录下所有的Python文件"""
directory = Path(directory)
# 遍历所有.py文件
for py_file in directory.rglob('*.py'):
# 跳过虚拟环境和隐藏目录
if any(part.startswith('.') or part == 'venv' or part == 'env' \
for part in py_file.parts):
continue
add_header_to_file(py_file)
if __name__ == '__main__':
directory = input("请输入要处理的项目目录路径: ")
process_directory(directory)
print("处理完成!")

