Saving matplotlib figures when running multiple subsequent python files via a .bat file on Windows

1 day ago 8
ARTICLE AD BOX

SET UP

I have multiple scripts that I execute with a .bat file, like so:

cd C:\path\to\my\project\directory echo Running script 1 "C:\ProgramData\miniforge3\envs\myenv\python.exe" script1.py echo. echo Running script 2 "C:\ProgramData\miniforge3\envs\myenv\python.exe" script2.py echo. echo Running script 3 "C:\ProgramData\miniforge3\envs\myenv\python.exe" script3.py echo. echo Complete! pause

MY ISSUE

Whenever I want to save an image with matplotlib's .savefig(), the current python script ends in its tracks, without error, and immediately skips to the next python file.

For example, if this is my script1.py:

import matplotlib.pyplot as plt print('Foo') x = [1,2,3,4] y = [1,2,3,4] plt.plot(x,y) plt.savefig('C:\path\to\my\project\directory\plots\plot.png') print('Bar')

This is what the console would print:

... C:\path\to\my\project\directory> echo Running script 1 Foo C:\path\to\my\project\directory>echo. C:\path\to\my\project\directory>echo Running script 2

This is a major issue as 1. my images don't get saved and 2. the rest of my code after the .savefig() call does not execute (no print of 'Bar').

WHAT I HAVE TRIED

I have tried adding the following, to no avail:

import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt

I tried using relative and absolute paths for the images I'd like to save, to no avail.

When I run script1.py in isolation via the command line, it runs flawlessly end-to-end with the images properly saved. This leads me to believe it has something to do with the .bat file.

This is really frustrating me as I have no idea why this wouldn't be working. I have saved matplotlib figures thousands of times with no issue, and saving this particular figure with no issue when running it from the command line in isolation, but the .bat file screws everything up. Is there something about .bat files I am unaware of?

I am using Windows 11, python 3.11.14, and maptlotlib 3.9.2

Read Entire Article