Pyinstaller exe 转换 matplotlib __init__ 错误

Posted

技术标签:

【中文标题】Pyinstaller exe 转换 matplotlib __init__ 错误【英文标题】:Pyinstaller exe convert matplotlib __init__ error 【发布时间】:2020-07-15 09:49:14 【问题描述】:

在尝试使用导入的 matplotlib 创建 .exe 时,出现以下错误:

Traceback(最近一次调用最后一次):文件“”,第 1 行,in 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 1015 行,在 rcParams = rc_params() 文件“C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py”, 第 878 行,在 rc_params 返回 rc_params_from_file(matplotlib_fname(), fail_on_error) 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 731 行,在 matplotlib_fname 中 对于 gen_candidates() 中的 fname:文件“C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py”, 第 728 行,在 gen_candidates 中 yield os.path.join(get_configdir(), 'matplotlibrc') 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 276 行,在包装器中 ret = func(**kwargs) 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 609 行,在 get_configdir 返回 _get_config_or_cache_dir(_get_xdg_config_dir()) 文件“C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py”, 第 562 行,在 _get_xdg_config_dir 返回 os.environ.get('XDG_CONFIG_HOME') 或 str(Path.home() / ".config") AttributeError: type object 'Path' has no attribute 'home' Traceback(最近一次调用最后一次):文件“”,第 1 行,在 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 1015 行,在 rcParams = rc_params() 文件“C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py”, 第 878 行,在 rc_params 返回 rc_params_from_file(matplotlib_fname(), fail_on_error) 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 731 行,在 matplotlib_fname 中 对于 gen_candidates() 中的 fname:文件“C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py”, 第 728 行,在 gen_candidates 中 yield os.path.join(get_configdir(), 'matplotlibrc') 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 276 行,在包装器中 ret = func(**kwargs) 文件 "C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py", 第 609 行,在 get_configdir 返回 _get_config_or_cache_dir(_get_xdg_config_dir()) 文件“C:\Users\Flo\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib__init__.py”, 第 562 行,在 _get_xdg_config_dir return os.environ.get('XDG_CONFIG_HOME') 或 str(Path.home() / ".config") AttributeError: type object 'Path' has no attribute 'home'

如果需要,这是我的代码:


from PIL import Image, ImageFont, ImageDraw
import urllib.request
import win32com
from win32com.shell import shell, shellcon
from win32com.client import Dispatch
from os import mkdir, remove, path
from datetime import date, datetime
#import winshell
#-------------------------------------------------------------------------------
# Name:        Modul1
# Purpose:
#
# Author:      Flo
#
# Created:     31.03.2020
# Copyright:   (c) Flo 2020
# Licence:     <your licence>
#-------------------------------------------------------------------------------
from datetime import date, datetime
import urllib.request
import zipfile
from shutil import copyfile, rmtree
import csv
import matplotlib.pyplot as plt
import time
start = time.time()
#-------------------------------------------------------------------------------
def datumedit(index, datumls, indexhinzufügen):
    ind = datumls.index(".")
    if ind != index:
        datumls.insert(indexhinzufügen, "0")
        ind += 1
    datumls[ind] = "-"
    return datumls
#-------------------------------------------------------------------------------
def csvdelim(liste, max):
    i = 0
    while i != max:
        ind = liste.index(";")
        liste[ind] = "-"
        i += 1
    retour = liste.index(";")
    return retour
#-------------------------------------------------------------------------------
def getvalues(file_dir,liste,liste2,ersetzenbis,floatconvertieren=False):
    durchlauf2 = 0
    keinedateninzeile = []
    with open(file_dir, newline='') as file1:
        anzahlreihen = sum(1 for line in file1)
    with open(file_dir, newline='') as file:
        reader = csv.reader(file)
        next(reader)
        for row in reader:
            durchlauf1 = 0
            uhrzeit = ""
            listed = ""
            reihe = list(str(row))
            ind = csvdelim(reihe,ersetzenbis)
            reihe[ind] = "-"
            ind1 = reihe.index(";")
            ind2 = ind+1
            inddif = ind1-ind-1
            while durchlauf1 != inddif:
                listed = listed+reihe[ind2]
                ind2 += 1
                durchlauf1 +=1
            if listed == "":
                continue
            if floatconvertieren == True:
                if listed == "":
                    None
                else:
                    liste.append(float(listed))
            else:
                liste.append(listed)

            if durchlauf2 == anzahlreihen:
                break
            indexuhzt = reihe.index(" ")
            uhrzeit = reihe[indexuhzt+1]+reihe[indexuhzt+2]+reihe[indexuhzt+3]+reihe[indexuhzt+4]+reihe[indexuhzt+5]
            liste2.append(uhrzeit)
            durchlauf2 += 1
    return liste, liste2
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
def bestimmtertag(datumin,orte,namen,temppath,bilderpfad,aktuellermonat,aktuellesjar,tag,monat,jahr):
    datumls = list(datumin)
    temp = temppath
    aus = False
    #CSV Herunterladen
    for e in orte:
        start1 = time.time()
        print(e)
        xpm25 = []
        xpm10 = []
        ypm25 = []
        ypm10 = []
        xpm10d = ""
        sensor = namen[e]
        if aktuellermonat == monat and jahr == aktuellesjahr:
            link = "https://www.madavi.de/sensor/data_csv/csv-files/%s-%s-%s/data-%s-%s-%s-%s.csv" %(jahr,monat,tag,sensor,jahr,monat,tag)
            iszip = False
        else:
            link = "https://www.madavi.de/sensor/data_csv/%s/%s/data-%s-%s-%s.zip" %(jahr,monat,sensor,jahr,monat)
            iszip = True
        if iszip == True:
            folderzip = "data-%s-%s-%s.zip" %(sensor,jahr,monat)
            folderohnezip = "data-%s-%s-%s" %(sensor,jahr,monat)
            filename = "data-%s-%s-%s-%s.csv" %(sensor,jahr,monat,tag)
            mkdir(temp+"\\"+folderohnezip, 0o777)
            with urllib.request.urlopen(link) as dl_file:
                with open(temp+"\\"+folderzip, 'wb') as out_file:
                    out_file.write(dl_file.read())
            with zipfile.ZipFile(temp+"\\"+folderzip, 'r') as zip_ref:
                zip_ref.extractall(temp+"\\"+folderohnezip)
            copyfile(temp+"\\"+folderohnezip+"\\"+filename, temp+"\\"+filename)
            rmtree(temp+"\\"+folderohnezip)
            remove(temp+"\\"+folderzip)

        else:
            filename = "data-%s-%s-%s-%s.csv" %(sensor,jahr,monat,tag)
            with urllib.request.urlopen(link) as dl_file:
                with open(temp+"\\"+filename, 'wb') as out_file:
                    out_file.write(dl_file.read())

        #CSV zu Liste
        getvalues(temp+"\\"+filename,ypm10,xpm10,6,True)
        print("marker1")
        getvalues(temp+"\\"+filename,ypm25,xpm25,7,True)
        remove(temp+"\\"+filename)
        #Graph
        plt.style.use("dark_background")
        plt.figure(dpi=600)
        ax = plt.subplot()
        ax.yaxis.grid(True)
        print("marker2")
        plt.plot(xpm10,ypm10,"r",label="PM10",linewidth=0.7)
        plt.plot(xpm25,ypm25,"g",label="PM25",linewidth=0.7)
        ax.legend(facecolor="#cccccc")#(211,211,211,1))
        print("marker3")
        ende1 = time.time()
        plt.savefig(bilderpfad+"\\"+e+".png", transparent=True)
        ende2 = time.time()
        print("marker4")
        plt.cla()
        plt.close("all")

        print('Einzelzeit: :5.3fs'.format(ende1-start1))
        print('Durchlauf: :5.3fs'.format(ende2-start1))

#-------------------------------------------------------------------------------
#
def bildtransparent(bild):
    img = Image.open(bild)
    img = img.convert("RGBA")
    datas = img.getdata()
    newData = []
    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
    img.putdata(newData)
    img.save(bild, "PNG")
#
print("Feinstaubdaten auslesen \nAutor: Florian Gruber \nDatum: 25.03.2020")
namen = "Festsaal":"esp8266-12774674","TH-Trakt":"esp8266-12775574", "Götzis":"esp8266-12775921", "Koblach":"esp8266-12776092"
orte = ["Festsaal", "TH-Trakt", "Götzis", "Koblach"]
bilderpfad = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0)
feinbilder = bilderpfad + "\\Feinstaub"
datumjetzt = datetime.now()
aktuellermonat = datumjetzt.strftime("%m")
aktuellesjahr = datumjetzt.strftime("%Y")
aktuellertag = datumjetzt.strftime("%d")
temp = feinbilder+"\\temp"
j = 1
zeitraum = False
größe = (1326,756)
höheobenzusatz = 0
höheuntenzusatz = 0
breitelinkszusatz = 0
breiterechtszusatz = 0
strichliste = [0,339,678,1017,1357,1696,1357+678,2375,2714]
uhrzeiten = ["00:00","03:00","06:00","09:00","12:00","15:00","18:00","21:00","24:00"]
#Ordner erstellen
try:
    mkdir(feinbilder, 0o775)
    print("Ordner erstellt")
except:
    None
try:
    mkdir(feinbilder+"\\temp", 0o777)
    print("Ordner erstellt")
except:
    None
##print(shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0))
##path1 = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0)+"\\Feinstaubdiagramme.lnk"
##desktop = winshell.desktop()
##target = path.abspath(__file__)
##shell = Dispatch('WScript.Shell')
##shortcut = shell.CreateShortCut(path1)
##shortcut.Targetpath = target
##shortcut.save()
##except:
##    print("Fehler")
#Bilder Downloaden
while True:
    datumin = "1.1.20"#input("Datum: ")
    datumls = datumedit(2, list(datumin), 0)
    datumls = datumedit(5, datumls, 3)
    if len(datumls) == 8:
        datumls.insert(-2,"2")
        datumls.insert(-2,"0")
    tag = datumls[0]+datumls[1]
    monat = datumls[3]+datumls[4]
    jahr = datumls[6]+datumls[7]+datumls[8]+datumls[9]
    datum = jahr+"-"+monat+"-"+tag
    try:
        mkdir(feinbilder+"\\"+datum, 0o775)
        print("Ordner erstellt")
    except:
        None
    if aktuellertag == tag and aktuellermonat == monat and aktuellesjahr == jahr:
        tage = 0#int(input("Anzahl Tage (0 für 24h): "))

        i = 1
        links = []
        if tage == 0:
            bzeitr = "24-Stunden"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-day.png" %sensor
                bild = open(feinbilder+"\\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        if tage > 1:
            bzeitr = "7-Tage"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-week.png" %sensor
                bild = open(feinbilder+"\\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        if tage > 7:
            bzeitr = "1-Monat"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-month.png" %sensor
                bild = open(feinbilder+"\\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        if tage > 31:
            bzeitr = "1-Jahr"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-year.png" %sensor
                bild = open(feinbilder+"\\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        zeitraum = True
    else:
        bestimmtertag(datumin,orte,namen,temp,feinbilder,aktuellermonat,aktuellesjahr,tag,monat,jahr)
        größenzusatz = True
    #Collage erstellen
    if größenzusatz == True:
        größe = (7080,5600)
        höheuntenzusatz = 2300
        höheobenzusatz = -203
        breitelinkszusatz = -80
        breiterechtszusatz = 2752
    collage = Image.new("RGB",größe,(0,0,0))
    draw = ImageDraw.Draw(collage)
    for e in orte:
        if j == 1:
            tup1 = (10+breitelinkszusatz,60+höheobenzusatz) # Position Einzelbild
            tup2 = (189,35) #Position Text Orte
            tup3 = (406,2424) #Rechteck Beginn
            tup4 = (3390,2550) #Rechteck Ende
            tup5 = [541,2454,541,199] # Linien erstellen Ausgangswerte
        elif j == 2:
            tup1 = (668+breiterechtszusatz,60+höheobenzusatz)
            tup2 = (3707,35)
            tup3 = (3896,2424)
            tup4 = (6880,2550)
            tup5 = [4031,2454,3930,199]
        elif j == 3:
            tup1 = (10+breitelinkszusatz,423+höheuntenzusatz)
            tup2 = (189,2903)
            tup3 = (406,5290)
            tup4 = (3390,5416)
            tup5 = [541,5320,541,3066]
        elif j == 4:
            tup1 = (668+breiterechtszusatz,423+höheuntenzusatz)
            tup2 = (3707,2903)
            tup3 = (3896,5290)
            tup4 = (6880,5416)
            tup5 = [4031,5320,3930,3066]
        bild = Image.open(feinbilder+"\\%s.png"%e)
        bild.copy()
        collage.paste(bild,tup1)
        bild.close()
        o = 0
        if größenzusatz == True:
            font = ImageFont.truetype("arial.ttf", 80)
            draw.rectangle((tup3, tup4), fill="black")
            for f in strichliste:
                if o == 9:
                    o = 0
                draw.line((tup5[0]+f,tup5[1],tup5[0]+f,tup5[3]),fill="white",width=3)#
                draw.text((tup5[0]-100+f,tup5[1]+6),uhrzeiten[o], fill="white",font=font)
                o += 1
        else:
            font = ImageFont.truetype("arial.ttf", 70)
        j += 1
        #Orte schreiben
        font = ImageFont.truetype("arial.ttf", 100)
        draw = ImageDraw.Draw(collage)
        draw.text(tup2,e,fill="white",font=font)
        draw.text((10,8),datum,(0,0,0),font=font)
        if zeitraum == True:
            draw.text((1230,8),bzeitr,(0,0,0),font=font)

    #Bild speichern
    if zeitraum == True:
        collage.save(feinbilder+"\\"+datum+"\\"+bzeitr+".png")
    else:
        collage.save(feinbilder+"\\"+datum+"\\"+datum+".png")
    #Einzelbilder löschen
    for e in orte:
        remove(feinbilder+"\\"+e+".png")
    #Bild öffnen
    collage.show()
    break

【问题讨论】:

【参考方案1】:

执行这个

pip uninstall pathlib

【讨论】:

以上是关于Pyinstaller exe 转换 matplotlib __init__ 错误的主要内容,如果未能解决你的问题,请参考以下文章

text PyInstaller - 将python脚本转换为.exe文件

Pyinstaller exe 转换 matplotlib __init__ 错误

python 使用pyinstaller生成exe

将python文件(.py)转换为可执行文件(.exe)的方法

使用 pyinstaller 将 python 文件转换为 .exe 给出: This application failed to start because no Qt platform plugi

使用Pyinstaller打包成EXE文件