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
cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog.
If you want the command prompt cmd widnow to stay open after executing the last command in batch file –you should write cmd /k command at the end of your batch file. This command will prevent the command prompt window from closing and you'll get the prompt back for giving more commands in the cmd window.
The easiest way of running a python script to run in the background is to use cronjob feature (in macOS and Linux). In windows, we can use Windows Task Scheduler. You can then give the path of your python script file to run at a specific time by giving the time particulars.
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.
Just Add Simple input At The End Of Your Program it Worked For Me
input()
Try it And It Will Work Correctly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With