首先找到两个文件: plugin.py 和 template.py ,目前最新版winpython的spyder两文件默认路径如下(其他版本和来源的应该也差不多)。
C:\WPy64-31090\python-3.10.9.amd64\Lib\site-packages\spyder\plugins\editor
C:\Users\${username}\.spyder-py3
通过修改 template.py 文件,比如常用包的导入,直接写入其中并保存即可;但更令人留意的是 %(username)s 和 %(date)s 两项,在新建文件时,它们将被替换,具体替换内容在 plugin.py 中,可搜索text = text % VARS跳转到对应内容,如下图所示(可能格式被我弄乱了,但内容应该一样)。
光标位置即替换语句,其中 text 为 template.py 文件内容的字符串,该语句对其进行格式化,将%(username)s 和 %(date)s 替换为字典 VARS 对应值。但这样简单的格式化可能由于文件中其他%的存在而报错,从而使新建的文件和模板文件完全一样。将其替换为
text = re.sub('"""(?:.|\n)*?"""', lambda m: m[0] % VARS, text)
使用 re 模块的替换函数,只替换第一个三引号括住的内容,能够防止这种情况。比如模板中有魔术命令,或是其他用到%的地方,可以防止其被错误地格式化而报错,从而提高模板文件的灵活性。
当然,其他魔改也是可以的,比如有人不爽默认的时间格式,可以将VARS中对应内容
'date': time.ctime(),
更改为
'date': time.strftime("%Y-%m-%d %H:%M"),
将时间格式改为更常见的年-月-日 小时-分钟格式。
最后分享一下自己的模板
# -*- coding: utf-8 -*-
"""
Created on %(date)s
@author: %(username)s
"""
# %matplotlib qt5
from matplotlib import font_manager
import numpy as np
from numpy import cos, sin, arctan2
import matplotlib.pyplot as plt
# import sympy as sp
# x=sp.symbols('x',cls=sp.Function)
# t=sp.symbols('t')
# from scipy.integrate import solve_ivp,quad
N, tspan = 1000, (0, 20)
t = np.linspace(*tspan, N, endpoint=False)
Change the way %(date)s and %(username)s are dealt with in template.py