LoginSignup
2
1

More than 1 year has passed since last update.

Flask でプロットしようとして、Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!となったときの回避方法

Last updated at Posted at 2022-05-30

概要

flask + pandas

を使っていて、
flask のエンドポイントの中でプロットをしてそれを保存したいだけだったのですが、

Terminating app due to uncaught exception 
'NSInternalInconsistencyException', 
reason: 'NSWindow drag regions should only be invalidated on the Main Thread!

となって落ちたときの備忘録を書きます。

TLDR

ここを見るだけでした。

flask のメイン関数を書いている python ファイルに、

import matplotlib
matplotlib.use('agg')

を追記するだけでした。

1分でできる再現方法

test.py
from flask import Flask, request
import numpy as np
import pandas as pd

app = Flask(__name__)


@app.route('/')
def index():
    tmp = (np.random.rand(100)*100).tolist()
    tmp2 = map(int, tmp)
    df = pd.DataFrame(tmp2, columns=["age"])
    df.plot.hist(bins=5).figure.savefig('static/tmp.png')

    return "hello, world"


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8000)

python test.py

で立ち上げた後、

curl localhost:8000

をすると、私の環境で(MacOS)

Terminating app due to uncaught exception 
'NSInternalInconsistencyException', 
reason: 'NSWindow drag regions should only be invalidated on the Main Thread!

となりました。

解決策

test.py
from flask import Flask, request
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')

app = Flask(__name__)

@app.route('/')
def index():
    tmp = (np.random.rand(100)*100).tolist()
    tmp2 = map(int, tmp)
    df = pd.DataFrame(tmp2, columns=["age"])
    df.plot.hist(bins=5).figure.savefig('static/tmp.png')

    return "hello, world"


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8000)

として、

import matplotlib
matplotlib.use('agg')

を追記してください。

まとめ

Mac環境でこのエラーとなった時は試してみてください。

今回はこの辺で。

@kenmaro

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1