Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Python closing immediately when executed in Microsoft Windows

Tags:

python

windows

I have just started college and we are going to be using python. We really have done nothing so I have downloaded the program and done some print commands, and that's it.

When I run my .py file (a print command) it immediately closes after appearing. I understand why it does this - it's given the output, so it's done what it needs to do - but I also understand that you can stop this from happening.

I looked around this website and none of the solutions given to this question worked, either that or I didn't understand them.

Is there a simple command I can input to my IDLE editor that will put the program on hold or something? I have tried input("prompt: ") as suggested by someone, and that made no difference.

If there isn't a command for this, is there a way to change the settings on the computer so that programs don't auto close?

like image 342
keirbtre Avatar asked Sep 11 '12 17:09

keirbtre


People also ask

How do I stop Python from automatically closing?

Use the -i Flag to Stop the Python Program From Closing Immediately. The -i flag is used to set the inspect flag to True when used in the command prompt. This prevents the program from exiting on SystemExit , so it can solve a Python program from closing immediately.

How do I stop Python from closing in cmd?

On windows, it's the CMD console that closes, because the Python process exists at the end. To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.

How do I make Python wait before closing?

You can add raw_input('Press Enter to exit') right before your program would exit. It tells Python to wait for input before exiting.

When trying to open a Python file Why does a black screen appear and disappear instantly?

The console appears and disappears because the program finishes, possibly very quickly, and you don't get to see the messages produced by the program.


2 Answers

In Python 3, add the following to the end of your code:

input('Press ENTER to exit') 

This will cause the program to wait for user input, with pressing ENTER causing the program to finish.

You can double click on your script.py file in Windows conveniently this way.

like image 188
Mike Avatar answered Sep 21 '22 10:09

Mike


The only thing that worked for me -i command line argument.

Just put all your python code inside a .py file and then run the following command;

python -i script.py 

It means that if you set -i variable and run your module then python doesn't exit on SystemExit. Read more at the this link.

like image 31
AnandShanbhag Avatar answered Sep 20 '22 10:09

AnandShanbhag