[python] How can I stop python.exe from closing immediately after I get an output?

Is there any way I can stop python.exe from closing immediately after it completes? It closes faster than I can read the output.

Here is the program:

width = float(input("Enter the width: "))
height = float(input("Enter the height: "))
area = width * height
print("The area is", area, "square units.")

This question is related to python

The answer is


Auxiliary answer

Manoj Govindan's answer is correct but I saw that comment:

Run it from the terminal.

And got to thinking about why this is so not obvious to windows users and realized it's because CMD.EXE is such a poor excuse for a shell that it should start with:

Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don't use this!!
C:>

Which leads me to point at https://stackoverflow.com/questions/913912/bash-shell-for-windows


Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program. Also, (assuming you have python 3), you can write:

input("Press enter to close program")

and you can just press enter when you've read your results.


It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.

A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:

C:\> cd C:\my_programs\
C:\my_programs\> python area.py

Replace my_programs with the actual location of your program and area.py with the name of your python file.


Just declare a variable like k or m or any other you want, now just add this piece of code at the end of your program

k=input("press close to exit") 

Here I just assumed k as variable to pause the program, you can use any variable you like.


For Windows Environments:

If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is better than inserting code into python that asks you to press any key - because if the program crashes before it reaches that point, the window closes and you lose the crash info. The solution I use is to create a bat file.

Use notepad to create a text file. In the file the contents will look something like:

my_python_program.py
pause

Then save the file as "my_python_program.bat"

When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.


In windows, if Python is installed into the default directory (For me it is):

cd C:\Python27

You then proceed to type

"python.exe "[FULLPATH]\[name].py" 

to run your Python script in Command Prompt