我编写了一个包,可以执行各种计算,还提供了多个绘图函数,并提供了将绘图保存为 .jpg 或 .png 格式的选项,保存在当前文件夹中的
plots
中。
工作目录。我确保该文件夹存在并带有装饰器
# plots.py
from my_package.params import out_path
def mkdir_plots(func):
@functools.wraps(func)
def wrapper_mkdir_plots(*args, **kwargs):
if not os.path.exists(out_path):
os.makedirs(out_path)
func(*args, **kwargs)
return wrapper_mkdir_plots
@mkdir_plots
def plot_fun1(vars):
# ...
plt.savefig(os.path.join(out_path, fname))
#params.py
out_path = 'plots'
def set_outpath(fname):
global out_path
out_path = fname
功能
set_outpath()
应该允许用户自己定义文件夹名称。函数 set_outpath()
将全局变量 params.out_path
设置为我喜欢的任何内容,但绘图模块将始终使用 'plots'
。
理想情况下,用户设置的变量
out_path
不仅可以从绘图模块(plot.py
)内访问,还可以从属于我的包的其他模块(calc.py
)访问,尽管这不是必须的。
好吧,这是基于 Barmar 评论的答案:
#params.py
out_path = 'plots'
def set_outpath(fname):
global out_path
out_path = fname
就像魅力一样!
# plots.py
from my_package import params
def get_outpath():
return params.out_path
def mkdir_plots(func):
@functools.wraps(func)
def wrapper_mkdir_plots(*args, **kwargs):
try:
os.makedirs(get_outpath())
except:
pass
func(*args, **kwargs)
return wrapper_mkdir_plots
@mkdir_plots
def plot_fun1(vars):
# ...
plt.savefig(os.path.join(out_path, fname))