简体   繁体   English

Pyinstaller - “致命错误! 将脚本转换为 exe 时无法执行脚本”

[英]Pyinstaller - “Fatal error ! Failed to execute script” when converting script to exe

I have a GUI built with tkinter, this makes webscraping by reading links from an excel file and then stores all the results in excel files.我有一个用 tkinter 构建的 GUI,它通过从 excel 文件中读取链接来进行网络抓取,然后将所有结果存储在 excel 文件中。 Also, it has buttons that allows plot de data from excel files doing some easy filters.此外,它还有一些按钮,允许 plot 从 excel 文件中获取数据,执行一些简单的过滤器。 I have it built correctly in Pycharm.我在 Pycharm 中正确构建了它。 Now, what I need is to built an exe file and for this I'm using pyinstaller with this code pyinstaller.exe --onefile --windowed main.py .现在,我需要构建一个 exe 文件,为此我使用 pyinstaller 和此代码pyinstaller.exe --onefile --windowed main.py The problem is that it gives a fatal error and fail to execute the script.问题是它给出了一个致命错误并且无法执行脚本。 I already tried to install all the packages in cmd in my enviroment, but the error persist.我已经尝试在我的环境中安装 cmd 中的所有软件包,但错误仍然存在。 Here I put my main.py (here the link to github where is functions.py and the input data):在这里我放了我的 main.py(这里是 github 的链接,其中是 functions.py 和输入数据):

from tkinter import messagebox
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfile
from functions import *
import os
import threading

excel_QS_resultados = os.path.dirname(__file__) + "/Resultados_QS"
excel_ponderacion_name = os.path.dirname(__file__) + "/Ponderación_Metologías"
def open_file():
    browse_text.set("Ejecutando...")
    file = askopenfile(parent = root, mode = "rb", title = "Elija un archivo", filetype = [("Excel file", "*.xlsx")])

    if file:
        if not os.path.exists(os.path.dirname(__file__) + "/Tablas"):
            os.mkdir(os.path.dirname(__file__) + "/Tablas")
        #print(os.getcwd())
        guardar_tablas(file.name[:-5], os.path.dirname(__file__) + "/Tablas",
                       excel_QS_resultados, root)
 
        browse_text.set("Cargar tablas de las webs de rankings")

def to_plot(kind, latam = False):
    file = askopenfile(parent=root, mode="rb", title="Elija un archivo", filetype=[("Excel file", "*.xlsx")])
    if file:
        if "QS" in os.path.basename(os.path.normpath(file.name[:-5])):
            ranking_name = "QS"
            subjects_QS = {0: os.path.basename(os.path.normpath(file.name[:-5]))[3:]}
            subjects_THE = {}
        else:
            ranking_name = "THE"
            subjects_THE = {0: os.path.basename(os.path.normpath(file.name[:-5]))[4:]}
            subjects_QS = {}

        df_subject = pd.read_excel(file.name)
        if ranking_name == "QS":
            list_years, list_years_2 = Get_If_UniRanked(df_subject, ranking_name, excel_QS_resultados, subjects_QS,
                                                        0)  # También imprime años rankeados

            list_years_rank = ["La PUCP fue rankeada en el año " + str(year) for year in list_years]
            list_years_result = ["Se tienen los resultados de la PUCP en el año " + str(year) for year in list_years_2]

            if list_years_rank == []:
                list_years_rank.append("La PUCP no fue rankeada en ninguno de los años")

            if list_years_result == []:
                list_years_result.append("No se tienen resultados de la PUCP en ninguno de los años")

            top = Toplevel(root)
            canvas2 = Canvas(top, width=600, height=300)
            canvas2.pack()

            header = Frame(canvas2, width=500, height=200, bg =  "#14a4d6")
            header.grid(columnspan=5, rowspan=2, row=0)

            header1 = Frame(canvas2, width=500, height=15, bg =  "#14a4d6")
            header1.grid(columnspan=3, rowspan=1, row=1)

            main_content = Frame(canvas2, width=500, height=100, bg="#14a4d6")
            main_content.grid(columnspan=5, row=2)

            display_text_box("\n".join(map(str, list_years_rank + list_years_result)), 0, 1, canvas2)

            instructions = Label(header1, text="Seleccione el año ",font="Raleway")
            instructions.grid(column=1, row=2)

            for i in range(len(list_years)):
                button = Button(main_content, text=list_years[i], font=("shanti", 10), height = 1, width = 6)
                button.grid(column=i, row=1, padx = 15, pady = 15)

        else:
            list_years = Get_If_UniRanked(df_subject, ranking_name, excel_QS_resultados, subjects_THE, 0)

            list_years_rank = ["La PUCP fue rankeada en el año " + str(year) for year in list_years]

            if list_years_rank == []:
                list_years_rank.append("La PUCP no fue rankeada en ninguno de los años")

            top = Toplevel(root)
            canvas2 = Canvas(top, width=600, height=300)
            canvas2.pack()

            header = Frame(canvas2, width=500, height=200, bg="#14a4d6")
            header.grid(columnspan=5, rowspan=2, row=0)

            header1 = Frame(canvas2, width=500, height=15, bg="#14a4d6")
            header1.grid(columnspan=3, rowspan=1, row=1)

            main_content = Frame(canvas2, width=500, height=100, bg="#14a4d6")
            main_content.grid(columnspan=5, row=2)

            display_text_box("\n".join(map(str, list_years_rank )), 0, 1, canvas2)

            instructions = Label(header1, text="Seleccione el año ", font="Raleway")
            instructions.grid(column=1, row=2)

    if kind  ==3:
        list_years = list_years_2[::-1]
    for i in range(len(list_years)):
        button = Button(main_content, text=list_years[i], font=("shanti", 10), height=1, width=6,
                        command =lambda i=i: plot(file, ranking_name, subjects_THE, subjects_QS, str(list_years[i]), kind, latam))
        button.grid(column=i, row=1, padx=15, pady=15)

def plot(file, ranking_name, subjects_THE, subjects_QS, year, kind, latam):
    df_subject = pd.read_excel(file.name)
    df_with_method = apply_methodology_continent(df_subject, excel_ponderacion_name, ranking_name, 0,
                                                 subjects_THE, subjects_QS).copy()
    time = datetime.datetime.now().time().strftime("%H-%M-%S")
    if ranking_name == "QS":
        df_with_method.to_excel(os.path.dirname(__file__) + "/" + ranking_name + " " + subjects_QS[0] + " " + time + ".xlsx",
                                index=False)
    elif ranking_name == "THE":
        df_with_method.to_excel(os.path.dirname(__file__) + "/" +  ranking_name + " " + subjects_THE[0] + " " + time + ".xlsx",
                                index=False)
    else:
        pass  # datetime.datetime.now().time().strftime("%H:%M:%S")

    if kind == 1:
        df_6Higher_Uni = Get_6Higher_Uni(df_with_method, int(year), ranking_name, latam)
        if df_6Higher_Uni is not None:
            Plot_6Higher_Uni(df_6Higher_Uni, ranking_name, latam)
            Plot_6HigherUni_Contribution(df_6Higher_Uni, excel_ponderacion_name, subjects_QS,
                                         subjects_THE, 0, ranking_name, latam)
        else:
            messagebox.showwarning("Advertencia",
                                   "Existen datos incompletos en el mismo rango de puestos que la PUCP. Analice un año anterior.")
    elif kind == 2:
        df_6Bottom_Uni = Get_6Bottom_Uni(df_with_method, int(year), ranking_name, latam)
        if df_6Bottom_Uni is not None:
            Plot_6Higher_Uni(df_6Bottom_Uni, ranking_name, latam)
            Plot_6HigherUni_Contribution(df_6Bottom_Uni, excel_ponderacion_name, subjects_QS,
                                         subjects_THE, 0, ranking_name, latam)
        else:
            messagebox.showwarning("Advertencia",
                                   "Existen datos incompletos en el mismo rango de puestos que la PUCP. Analice un año anterior.")
    else:
        df_6Bottom_Uni = Get_6Bottom_Uni_QS_Result(df_with_method, int(year), excel_ponderacion_name,
                                                   excel_QS_resultados, 0, subjects_QS, latam)
        if df_6Bottom_Uni is not None:
            Plot_6Higher_Uni(df_6Bottom_Uni, ranking_name, latam)
            Plot_6HigherUni_Contribution(df_6Bottom_Uni, excel_ponderacion_name, subjects_QS,
                                         subjects_THE, 0, ranking_name, latam)
        else:
            messagebox.showwarning("Advertencia",
                                   "Existen datos incompletos en el mismo rango de puestos que la PUCP. Analice un año anterior.")

root = Tk()
root.iconbitmap("C:/Users/Franco/PycharmProjects/THE_QS/icon.ico")
root.title("Generador de gráficos- Rankings THE y QS by Subject")

header = Frame(root, width=800, height=150)
header.grid(columnspan=3, rowspan=2, row=0)

main_content = Frame(root, width=800, height=150, bg="#14a4d6")
main_content.grid(columnspan=3, rowspan=4, row=4)

btn_options = ["R - Siguientes 6 Univ. Rankeadas Global",
                    "R - Siguientes 6 Univ. Rankeadas LATAM",
                    "NR/R - Últimas 6 Universidades Rankeadas Global",
                    "NR/R - Últimas 6 Universidades Rankeadas LATAM",
                    "NR - QS Últimas Universidades Rankeadas Global",
                    "NR - QS Últimas Universidades Rankeadas LATAM"]


next6Global_btn = Button(root, text = btn_options[0], font=("shanti", 10), height = 1, width = 40, command = lambda: to_plot(kind = 1))
next6Latam_btn = Button(root, text = btn_options[1], font=("shanti", 10), height = 1, width = 40, command = lambda: to_plot(kind = 1, latam=True))
last6Global_btn = Button(root, text = btn_options[2], font=("shanti", 10), height = 1, width = 40, command = lambda: to_plot(kind = 2))
last6Latam_btn = Button(root, text = btn_options[3], font=("shanti", 10), height = 1, width = 40, command = lambda: to_plot(kind = 2, latam=True))
QSlast6Global_btn = Button(root, text = btn_options[4], font=("shanti", 10), height = 1, width = 40, command = lambda: to_plot(kind = 3))
QSlast6Latam_btn = Button(root, text = btn_options[5], font=("shanti", 10), height = 1, width = 40, command = lambda: to_plot(kind = 3, latam=True))

next6Global_btn.grid(row = 4, column = 1)
next6Latam_btn.grid(row = 4, column = 2)
last6Global_btn.grid(row = 5, column = 1)
last6Latam_btn.grid(row = 5, column = 2)
QSlast6Global_btn.grid(row = 6, column = 1)
QSlast6Latam_btn.grid(row = 6, column = 2)

# logo
display_logo("C:/Users/Franco/PycharmProjects/THE_QS/pucp-logo.png", 0, 1)

# instructions
instructions = Label(root, text="Seleccione el archivo excel con los enlaces de los rankings by subject", font="Raleway")
instructions.grid(columnspan=4, rowspan= 3, column=1, row=1)


# browse
browse_text = StringVar()
browse_text.set("Cargar tablas de las webs de rankings")
browse_btn = Button(root, textvariable = browse_text, font="Raleway", bg="#14a4d6",
                       command = lambda: threading.Thread(target=open_file).start(), fg="white", height=2, width=35)

browse_btn.grid(columnspan = 3, column=1, row=2)


root.mainloop()

I really appreciate some help on this because I've already tried some time and don't get it works.我真的很感谢这方面的一些帮助,因为我已经尝试了一段时间并且没有得到它的工作。


UPDATE更新

After some months left this project without finished, I wanted to prove some of the new suggestion from yours I got.在几个月没有完成这个项目之后,我想证明我从你那里得到的一些新建议。 I tried with @Blueman7 suggestion about missing icon=part and the commands I used in cmd are the following (In case I made an error in execution, because it still doesn't work but there's some improvement):我尝试了@Blueman7 关于缺少icon=part的建议,我在 cmd 中使用的命令如下(如果我在执行时出错,因为它仍然不起作用,但有一些改进):

  • cd project_path cd 项目路径
  • conda activate environment_name conda 激活 environment_name
  • pyinstaller.exe --onefile --icon=icon.ico main.py pyinstaller.exe --onefile --icon=icon.ico main.py

After this commands are executed I got a main.exe with my icon.ico.执行此命令后,我得到了一个带有 icon.ico 的 main.exe。 When I try to run this.exe, it opens a black window and keeps like that for around 1 minute when it gives the error in this image which is related pyzmq package.当我尝试运行 this.exe 时,它会打开一个黑色的 window 并在此图像中给出与 pyzmq package 相关的错误时保持这种状态大约 1 分钟。

在此处输入图像描述

I tried copy this folder pyzmq.libs to my current project path and run the command pyinstaller.exe --onefile --icon=icon.ico --add-data "./pyzmq.libs;." main.py我尝试将此文件夹 pyzmq.libs 复制到我当前的项目路径并运行命令pyinstaller.exe --onefile --icon=icon.ico --add-data "./pyzmq.libs;." main.py pyinstaller.exe --onefile --icon=icon.ico --add-data "./pyzmq.libs;." main.py in cmd. pyinstaller.exe --onefile --icon=icon.ico --add-data "./pyzmq.libs;." main.py中的 main.py。 Also, I tried importing pyzmq to my conda environment, nut it neither works so far.另外,我尝试将 pyzmq 导入我的 conda 环境,但到目前为止它都不起作用。 Thanks a lot for the suggestions.非常感谢您的建议。

Giving a screenshot of what error you have obtained is always helpful to understand your problem.提供您获得的错误的屏幕截图始终有助于理解您的问题。

But from information you have given,I think your problem is with the command your are using and it should be,但是根据您提供的信息,我认为您的问题出在您正在使用的命令上,应该是,

pyinstaller --onefile --windowed main.py

for detailed information on how to create executable using pyinstaller have a look at this -> https://datatofish.com/executable-pyinstaller/有关如何使用 pyinstaller 创建可执行文件的详细信息,请查看此 -> https://datatofish.com/executable-pyinstaller/

if this didn't works then try using py2exe如果这不起作用,请尝试使用py2exe

and have a look at this,看看这个,

https://stackabuse.com/creating-executable-files-from-python-scripts-with-py2exe https://stackabuse.com/creating-executable-files-from-python-scripts-with-py2exe

Try:尝试:

pyinstaller onefile -w main.py

Is this working?这管用吗?

What worked for me is just:对我有用的只是:

pyinstaller --onefile main.py

without -windowed or -w没有 -windowed 或 -w

In your code you forgot to mention the icon=part.在您的代码中,您忘记提及 icon=part。

pyinstaller.exe --onefile --windowed --icon=yourico.ico main.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PyInstaller 致命错误:无法执行脚本 - PyInstaller fatal error: Failed to execute script Pyinstaller exe执行脚本失败 - Pyinstaller exe failed to execute script PyInstaller 从 .py 转换为 .exe 时执行脚本失败 - PyInstaller Failed to execute script while converting from .py to .exe 使用 pyinstaller 转换为 .exe 后退出 pygame 窗口而未打开控制台时出现“无法执行脚本 myscript” - "Failed to execute script myscript" when exiting pygame window without console open after converting to .exe with pyinstaller 尝试运行 pyinstaller 创建的 .exe 文件时“执行脚本失败” - “Failed to execute script” when trying to run .exe file created by pyinstaller Pyinstaller - “致命错误! 使用 multiprocessing.freeze_support 时无法执行脚本” - Pyinstaller - “Fatal error ! Failed to execute script” when using multiprocessing.freeze_support Pyinstaller执行脚本失败 - Pyinstaller Failed execute script Error PyInstaller“无法执行脚本”错误 - PyInstaller “failed to execute script” Error Pyinstaller - Python exe 运行时显示错误“无法执行脚本 pyi_rth_nltk” - Pyinstaller - Python exe when run shows error “Failed to execute script pyi_rth_nltk” 致命错误:无法执行“脚本名称”| 自动 py 到 exe - Fatal Error: Failed to execute "script name" | auto-py-to-exe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM