Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeError: main thread is not in main loop with Matplotlib and Flask

Tags:

I'm using flask, matplotlib to save image and tensorflow to create a session. I'm getting the above error when I run the following code. Does the flask route run on a separate thread? How can I make fig.saveFig piece of code run on the Main thread. Thanks a lot

 @app.route('/open', methods = ['GET', 'POST'])
 def sendOutput():
     global loss,a2,xP,yP,scale,sess,fig
     test_X,test_Y = own_model.getEvaluateData(scale)
     cost,ans = sess.run([loss,a2],feed_dict={xP:test_X,yP:test_Y})
     d = np.array(ans) - np.array(test_Y)
     val = hist(d,100)
     sess.close()
     fig.saveFig('abc.png') //Errror on this line
like image 569
Mihir Prabhudesai Avatar asked Apr 19 '18 12:04

Mihir Prabhudesai


1 Answers

I was on the same situation, Flask with Matplotlib combo. What worked for me is to specify Agg as Matplotlib backend.

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

# Your code here

You can refer to Matplotlib documentation (Matplotlib in a web application server) for the details.

like image 176
CpK Avatar answered Oct 17 '22 06:10

CpK