在 cmd 中运行并作为独立的 exe 文件运行时,简单的 python 文件崩溃而不打印输出。不知道为什么

问题描述 投票:0回答:1

因此该程序在 PyCharm(我创建它的地方)中运行良好并打印出生年份。但是,当我在 cmd 中运行 .py 文件并作为独立的 exe 文件(用 pyinstaller 制作)时,我只能到达提供年龄输入的位置,然后当我按出生年份的“Enter”键时输出,程序在最后一步之前崩溃。下面是代码:

# 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='.')

python python-3.x pyinstaller
1个回答
0
投票

程序没有崩溃,只是完成了。一旦用户输入了他们的年龄,它就会运行到最后几行:

current_year = 2023
birth_year = current_year - age
print()
print('Hello', name + '!', 'You were born in', birth_year, end='.')

但是由于它到达了文件末尾,程序认为它已完成,并在您实际看到最后一个

print()
语句的输出之前为您关闭窗口。在 PyCharm 中,它可能会返回到终端,这就是为什么它似乎在那里工作正常。

如果将

input("Press enter to exit")
添加到代码末尾,程序将执行最后几行,然后等待用户发送另一行(按 Enter 键)。即使这是使用
input()
函数完成的,程序也会在到达程序末尾时丢弃输入并退出。

© www.soinside.com 2019 - 2024. All rights reserved.