Python程序在CMD及PyInstaller生成的EXE中运行崩溃无输出求助
Python程序在CMD/EXE运行时崩溃的解决办法
你遇到的问题是:这段代码在PyCharm中运行正常,但在CMD直接运行.py文件,或用PyInstaller打包成EXE后,输入年龄回车程序就崩溃。
可能的原因
- 输入格式错误:如果输入的年龄不是纯整数(比如带空格、中文、字母),
int(input(...))会抛出ValueError导致程序崩溃,PyCharm中你可能输入的都是合法整数,所以没触发该问题。 - 控制台编码不兼容:CMD默认编码为GBK,Python默认输出编码是UTF-8,若输入的名字包含中文,可能导致输出时编码冲突引发崩溃。
- EXE窗口瞬间关闭:打包后的EXE运行结束后会立即关闭控制台窗口,你可能误以为是崩溃,实际程序已经执行完成。
解决方案
1. 捕获输入异常,避免程序崩溃
修改年龄输入部分,添加异常处理逻辑,确保输入非整数时程序不会崩溃,还能提示用户重新输入:
# Capture name and age name = input('What is your name? ') while True: try: age = int(input('How old are you? ')) break except ValueError: print("请输入有效的数字年龄!") # Calculate birth year and output current_year = 2023 birth_year = current_year - age print() print('Hello', name + '!', 'You were born in', birth_year, end='.')
2. 解决编码兼容问题
在程序开头添加编码声明,同时强制输出使用GBK编码以适配CMD:
# -*- coding: utf-8 -*- import sys sys.stdout.reconfigure(encoding='gbk') # Capture name and age name = input('What is your name? ') age = int(input('How old are you? ')) # Calculate birth year and output current_year = 2023 birth_year = current_year - age print() print('Hello', name + '!', 'You were born in', birth_year, end='.')
3. 让EXE运行后保持窗口打开
在程序末尾添加输入等待语句,避免窗口运行结束后瞬间关闭:
# Capture name and age name = input('What is your name? ') age = int(input('How old are you? ')) # Calculate birth year and output current_year = 2023 birth_year = current_year - age print() print('Hello', name + '!', 'You were born in', birth_year, end='.') # 等待用户输入再关闭窗口 input("\n\nPress Enter to exit...")
内容的提问来源于stack exchange,提问作者superior_light
相关产品推荐
相关产品推荐

