使用PyInstaller打包的Python程序未打印结果即退出,求助排查
解决PyInstaller打包exe后程序提前退出无法查看结果的问题
问题原因
双击运行控制台类型的exe时,程序执行完所有代码后会立即关闭控制台窗口,导致你还没看到最终的打印结果窗口就消失了。
解决方法
方法1:在代码末尾添加暂停逻辑
直接修改Python代码,在最后一行print之后添加等待用户输入的代码,让程序在退出前等待用户操作:
print("Welcome to the Shen Ho's Lunch Expenses Calculator! :)") bill = float(input("What was the total bill? RM ")) tax = int(input("How much percent of service tax in the bill? ")) people = int(input("How many people to split the bill? ")) total_tax_amount = (bill * tax) / 100 total_bill = bill + total_tax_amount bill_per_person = total_bill / people final_amount = round(bill_per_person, 2) print(f"Each person should pay: RM{final_amount}") # 添加这行代码,等待用户按回车再退出 input("Press Enter to exit...")
修改后重新用PyInstaller打包,双击运行exe时,打印完结果后会停在窗口,直到你按回车键才关闭。
方法2:通过命令行运行exe
- 打开Windows命令提示符(CMD)
- 用
cd命令导航到exe文件所在的文件夹,比如cd D:\your_exe_folder - 输入exe文件名并回车运行,比如
your_program.exe
这种方式下,程序执行完后控制台窗口不会自动关闭,你可以清楚看到所有输出内容。
内容的提问来源于stack exchange,提问作者Shen
相关产品推荐
相关产品推荐

