首页 > 解决方案 > Python 文件在 VSCode 中工作,但在作为可执行文件运行时会自动崩溃

问题描述

初学者在这里

我正在开发一个程序,该程序可以计算 3D 打印机打印(通过 Cura Slicer)所需的估计时间与实际时间之间的累积误差。我想使用 pyinstaller 将程序作为可执行文件运行,但是可执行文件打开的命令提示符会自动关闭。我可以使用 运行可执行文件并关闭窗口input("Press any key to stop the program: "),但是在我实现try: error_list=[]...except ZeroDivisionError: print("Sorry, there's nothing in this file").终端窗口后,它会在运行时关闭。请记住,我在 VSCode 中测试了代码,并且input()按预期工作,但是在终端中作为可执行文件它会自动关闭。

为什么程序在 VSCode 中可以正常运行,但在作为可执行文件运行时会自动关闭?任何帮助是极大的赞赏!

要在 cmd 中安装可执行文件,我使用pyinstaller .\CuraTimeError.py

    def getError():
        f=open("errors.txt","r")
        data=f.read()
        try:  
            error_list=[]
            interations=iter(data)
            for char in range(len(data)):
                try:
                    thing=next(interations)
                except(StopIteration):
                    continue
                if thing == "*":
                    error=float(next(interations)+next(interations)+next(interations)+next(interations))
                    error_list.append(error)
            print("The current total error is: " +str(sum(error_list)/len(error_list)))
            f.close()
        except ZeroDivisionError:
            print("Sorry, there's nothing in this file")

    getError()
    numberOfCases=int(input("How many tests are you inputting? "))
    if numberOfCases != 0:
        print("NOTE: Time follows 24-hour notation")
        for i in range(numberOfCases):
            print("Please enter case number "+str(i+1))
            f=open("errors.txt","a")
            curaTime=input("Cura estimated time: ")
            startTime=input("Start time: ")
            endTime=input("End time: ")
            if int(endTime)<int(startTime):
                endTime = str(int(endTime)+2400)
            actualTime=60*(int(endTime[0:2])-int(startTime[0:2]))+(int(endTime[2:4])-int(startTime[2:4]))
            estimatedTime= 60*(int(curaTime[0:2]))+int(curaTime[2:4])
                    error=(actualTime-estimatedTime)/(estimatedTime)+1
                    f.write(curaTime+","+startTime+","+endTime+",*"+str(round(error,2))+"\n")
                    f.close()
    getError()
    input("Press any key to stop the program: ")

标签: pythonpyinstallerexecutable

解决方案


我无法找到直接解决此问题的方法,因此解决方法是通过在文件中添加一行已知数据来消除对try...except ZeroDivisionErrorunder 函数的需求。这样,在尝试此 try-except 时可执行文件不会崩溃。getError()errors.txt


推荐阅读