简体   繁体   English

运行程序后窗口立即关闭

[英]Window closes immediately after running program

I am new to all programming and I just started to get interested in learning how to program. 我是所有程序设计的新手,我刚开始对学习如何编程感兴趣。 So to do so I started with what most people consider the easiest language: Python. 为此,我从大多数人认为最简单的语言开始:Python。

The problem I am having right now though is that if I say to Python print("Hello!") , save it in a file, and then run it, a black window opens up and closes right away. 我现在遇到的问题是,如果我对Python print("Hello!") ,将其保存在文件中,然后运行它,则会打开一个黑色窗口并立即关闭。 I just do not understand why it is doing this. 我只是不明白为什么要这么做。

It is normal for the window to close as soon as your program runs to completion. 程序运行完成后,通常会关闭窗口。 If you want it to stay open, you can add a call to input (or raw_input if you are using Python 2.x) at the end: 如果希望它保持打开状态,则可以在最后添加对input的调用(如果使用的是Python 2.x,则可以添加raw_input ):

print("Hello!")
input("Press the <Enter> key on the keyboard to exit.")

This will keep the window open until you press the Enter key on the keyboard. 这将使窗口保持打开状态,直到您按键盘上的Enter键。

Well because a print command simply writes something to the terminal. 好吧,因为print命令只是在终端上写一些东西。

In order to see the output. 为了输出。 Start cmd (or open a terminal in Linux) and then run: 启动cmd (或在Linux中打开终端),然后运行:

python <file>

with <file> the file you want to run... 使用<file>您要运行的文件...

Or you can, like @iCodez suggests, pause the input at the end of the program by adding a pause: 或者,您可以像@iCodez建议的那样,在程序末尾通过添加暂停来暂停输入:

print("Hello World!")
input()

Insert input() in the last line. 在最后一行插入input()。 It will make the program wait for a input. 它将使程序等待输入。 While it doesn't occur the windows program will be open. 虽然没有发生,但Windows程序将打开。 If you press any key and then enter, it will close. 如果按任意键然后输入,它将关闭。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM