Aakash
Aakash

Reputation: 347

How to stop command prompt from closing in python?

I am very new to python.. I used the code

x = input(" Hey what is your name " )       
print(" Hey, " + x)  
input(" press close to exit ")

Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help

I am using python 3.3

Upvotes: 11

Views: 95684

Answers (5)

Mohammed Ouedrhiri
Mohammed Ouedrhiri

Reputation: 159

Just Add Simple input At The End Of Your Program it Worked For Me

input()

Try it And It Will Work Correctly

Upvotes: 2

yourson
yourson

Reputation: 86

Try this,

import sys

status='idlelib' in sys.modules

# Put this segment at the end of code
if status==False:
    input()

This will only stop console window, not the IDLE.

Upvotes: -1

Inter Mob
Inter Mob

Reputation: 31

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 gooThe 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" - DO NOT FORGET TO SELECT "All Files!

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.

Upvotes: 3

Blaze
Blaze

Reputation: 1722

That can be done with os module. Following is the simple code :

import os
os.system("pause")

This will generate a pause and will ask user to press any key to continue.

[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that "os" library is operating system specific and some commands might not work with one operating system like they work in another one.]

Upvotes: 16

Martijn Pieters
Martijn Pieters

Reputation: 1124558

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.

The alternative is, as you've found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.

Upvotes: 24

Related Questions