簡體   English   中英

Matplotlib 和 :RuntimeError: 主線程不在主循環中:

[英]Matplotlib and :RuntimeError: main thread is not in main loop:

我正在嘗試在 python 下並行運行多個重復性任務。 我對多處理很陌生,但由於所有任務都是獨立的,我使用了以下簡單的代碼:

    import numpy as np
    import sys
    import os
    import glob
    import matplotlib.pyplot as plt
    import concurrent.futures as Cfut

    def analize(simul, N_thread):
        path = os.getcwd()

        print('Analizing topo ...')
        Data = output of some calculations

        print('Writing Data ...')
        np.save('Data', Data)

        print('Data saved')
        print('Printing figures')

        plt.figure()
        plt.plot(Data[0])
        plt.savefig('figure1.pdf)

        plt.clf()
        plt.plot(Data[0])
        plt.savefig('figure1.pdf)

        plt.close('all')
        print('figures saved')
        os.chdir(path

if __name__ == '__main__':
    list_simul = sorted(glob.glob('Layer*'))
    executor = Cfut.ProcessPoolExecutor(5)
   #executor = Cfut.ThreadPoolExecutor(N_jobs)
    futures = [executor.submit(analize, item, 10) for item in list_simul]
    Cfut.wait(futures)

它在 3 個月內運行良好,從早上開始我有時會收到以下錯誤:

Exception ignored in: <bound method Image.__del__ of <tkinter.PhotoImage object at 0x7fac6c187f98>>
    Traceback (most recent call last):
      File "/usr/lib/python3.5/tkinter/__init__.py", line 3359, in __del__
        self.tk.call('image', 'delete', self.name)
    RuntimeError: main thread is not in main loop

奇怪的是,有些工作可以毫無問題地完成,而且並非總是如此。 通過一些研究,我發現了很多關於這個問題的帖子,它們都與 GUI 相關。 我理解這個問題,但我想我應該能夠找到一種解決方法,因為我沒有顯示任何圖形,只是創建對象並保存它,並且因為所有任務都是獨立的。

任何提示?

正如所看到這里,你有沒有嘗試添加以下代碼到您的進口頂部?

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

matplotlib 默認使用TkAgg TkAggFltkAggGTKGTKAggGTKCairoWxWxAgg都是基於 GUI 的。 並且大多數 GUI 后端需要從主線程運行。 因此,如果您在沒有 GUI 的環境中運行,它將拋出RuntimeError: main thread is not in main loop

因此,只需切換到不使用 GUI 的后端: AggCairoPSPDFSVG

例如:

import matplotlib.pyplot as plt
plt.switch_backend('agg')

參考資料: https : //matplotlib.org/stable/faq/howto_faq.html#work-with-threads

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM