简体   繁体   中英

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

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.

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.]

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.

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.

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

input()

Try it And It Will Work Correctly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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