I have a simple gui which launches a subprocess that starts the python interpreter in interactive mode as follows:
pyproc = subprocess.Popen([".venv\Scripts\python", "-i"], bufsize = 1, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
I have no problems reading stderr, stdout and writing to stdin. I now want to run matplotlib commands in the console and am having a problem. The following commands run as expected
import matplotlib.pyplot as plt
plt.plot([1,2,1,2,1,2,1])
I cannot display the plot though when I run
plt.show()
The python interpreter is blocked as it is probably expecting me to close the plot window. this window never appears though. I think it has something to do with the python interpreter being part of the subprocess but do not understand what exactly. Could someone shed some light on this?
I have tried interactive mode. In interactive mode, the plot window is displayed but the interpreter appears to be blocked even when I close the plot window.
The issue you’re facing when trying to run matplotlib
in a Python interpreter within a subprocess is due to the way GUI toolkits (such as those used by matplotlib) interact with event loops. When you invoke plt.show()
, it opens a window and starts an event loop to handle the GUI rendering and interaction.
However, this loop blocks the interpreter because the subprocess is waiting for the window to close before continuing. In your case, since the subprocess is being controlled via stdin
and stdout
, it doesn’t handle GUI windows correctly.
You can enable interactive mode with plt.ion()
, which allows the plot to be displayed without blocking.
1