How to stop command prompt from closing in python? - 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.

Just Add Simple input At The End Of Your Program it Worked For Me
input()
Try it And It Will Work Correctly

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.

Related

How to refresh/overwrite console output in python

I want to know how to refresh the console of my program as if it was just started. Let's say that my code consists of an infinite loop and it has multiple instances of the print() function within itself, I want, every time that loops returns to its start, all the new data whether there is some change or not to get outputted on the same place of the data that has been outputted the last time.
I have been reading about similar problems others have posted and the answers usually revolve around the idea of using \r, when I do that, however, it's always messy and the strings are either printed halfway or there are missing characters. On Replit there is a module called "replit" and there is a function there called clear() that basically performs what I need, but I don't seem to find it when I am using PyCharm, which means that it is perhaps something that works exclusively within the Replit environment. So I am asking, is there something similar in the standard python library that I can use? Thanks
You can use:
import os
command = 'cls' #for windows
os.system(command)
example:
print('hi')
os.system(command)
print('hi')
Output:
hi
For windows you need:
command = 'cls'
For all others it is:
command = 'clear'
To account for any OS you could use:
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If computer is running windows use cls
command = 'cls'
os.system(command)
clearConsole()
There is nothing standard in Python to do it, because Python is not aware of whatever console you are using.
When you call print it is actually writing to a file called "standard output".
It can go to a console if you are running your program in a console (like windows cmd, Linux or Mac OS terminal app, or whatever PyCharm uses).
But it can also be redirected to a regular file by the user of your program.
So there is no standard way.
\r is "carriage return" character. On consoles that respect it, it will set your output position to the beginning of the current line, but will not erase any text already printed on that line (usually).
One way to print text in specific places on the screen is PyCurses.
It supports many consoles and figures out which one you are using automatically.
You can do something like this:
import curses
stdscr = curses.initscr()
stdscr.addstr(x, y, "my string")
By using the addstr isntead of print, you can choose the exact position the text will appear, with X and Y coordinates (first two parameters).
Read the documentation for more ways to manipulate text display with this library.

Running batch file with subprocess.call does not work and freezes IPython console

This is a frequent question, but reading the other threads did not solve the problem for me.
I provide the full paths to make sure I have not made any path formulation errors.
import subprocess
# create batch script
myBat = open(r'.\Test.bat','w+') # create file with writing access
myBat.write('''echo hello
pause''') # write commands to file
myBat.close()
Now I tried running it via three different ways, found them all here on SO. In each case, my IDE Spyder goes into busy mode and the console freezes. No terminal window pops up or anything, nothing happens.
subprocess.call([r'C:\\Users\\felix\\folders\\Batch_Script\\Test.bat'], shell=True)
subprocess.Popen([r'C:\\Users\\felix\\folders\\Batch_Script\Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
p = subprocess.Popen("Test.bat", cwd=r"C:\\Users\\felix\\folders\\Batch_Script\\")
stdout, stderr = p.communicate()
Each were run with and without the shell=True setting, also with and without raw strings, single backslashes and so on. Can you spot why this wont work?
Spyder doesn't always handle standard streams correctly so it doesn't surprise me that you see no output when using subprocess.call because it normally runs in the same console. It also makes sense why it does work for you when executed in an external cmd prompt.
Here is what you should use if you want to keep using the spyder terminal, but call up a new window for your bat script
subprocess.call(["start", "test.bat"], shell=True)
start Starts a separate Command Prompt window to run a specified program or command. You need shell=True because it's a cmd built-in not a program itself. You can then just pass it your bat file as normal.
You should use with open()...
with open(r'.\Test.bat','w+') as myBat:
myBat.write('echo hello\npause') # write commands to file
I tested this line outside of ide (by running in cmd) and it will open a new cmd window
subprocess.Popen([r'Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
Hey I have solution of your problem :)
don't use subprocess instead use os
Example :
import os
myBatchFile = f"{start /max} + yourFile.bat"
os.system(myBatchFile)
# "start /max" will run your batch file in new window in fullscreen mode
Thank me later if it helped :)

How to check for a running shell in windows?

I try to write a programm in python that notifies me, when a shell like cmd gets opened.
Until now I did the following in python.
Check for new starting processes, get the name of the process and check if its name is cmd.exe.
This works if I start a cmd process manually myself.
But it Turns out if i open a shell with subprocess.getoutput(command) from the subprocess library in python there is no shell listed in the prosesses and I also cant see it in taskmanager.
So I assumed its a childprocess of the pythonscripts process running?
My next Idea was to list all the modules a process is using and check for cmd.exe in the modules.
It turns out the pythonscript with subprocess.getoutput(command) does not use cmd.exe in the modules. Strange.
So right now I am not sure how I could detect the shell or if I am even on the right way.
Maybe I need to find the childprocesses of a the pythonprocess? Or is it possible to get a shell without calling cmd.exe I honestly dont know enough about it.
Maybe its better to check for chertain dlls in the used methods by a process?
I also tried to look in the subprocess.py library but it is difficult for me to understand and it seems to atleast pass over cmd as a parameter for subprocess.getoutput() method.
Can somebody help?
Thank you.
UPDATE:
I use this code to detect the process:
import wmi
c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
print(new_process.Caption, new_process.ProcessId)
if new_process.Caption =="cmd.exe":
pid = new_process.ProcessID
break
But if I run this code
import subprocess
output = subprocess.getoutput("ipconfig")
print(output)
The only process detected is pythonw.exe
But if I run
import subprocess
while True:
output = subprocess.getoutput("ipconfig")
print(output)
At some point it find cmd.exe.
So I assume that wmi takes to long to detect the process. So cmd is already closed and does not get found.
Any Ideas how to do this a better way?
I didnt know practic version of solution.But you can use pyautogui for it if you want.You can write a program with pyautogui that notifies you when it find cmd logo at task bar.Example:
import pyautogui
cmdlogo = pyautogui.locateOnScreen('get screenshot of cmd logo and write file name here example:'cmd.png'')
While True:
if cmdlogo:
print('write here what yo want to say when it finds cmd')
else:
pyautogui.sleep(5)

Some Python scripts CMD windows closes immediately

Some of my python (3.6) scripts will close immediately when run. Others, however, do not. The script in question will copy a selected text and look up the word on dictionary.com. When I run the script from Pycharm, it works as intended. However, when I run it from the search bar or double-click the file from within the folder, it immediately closes. I have tried using input("something") and time.sleep(1) but with no luck. I also have success with opening a command window and typing python dictionary.py and enter.
This is what the body looks like:
import pyperclip
import keyboard
import pyautogui
import time
def lookup():
prev = pyperclip.paste()
time.sleep(.1)
pyautogui.hotkey('ctrl', 'c')
time.sleep(.1)
word = pyperclip.paste()
url = f"https://www.dictionary.com/browse/{word}?s=t"
webbrowser.open(url)
pyperclip.copy(prev)
def switch_back():
pyautogui.keyDown('ctrl')
pyautogui.press("w")
pyautogui.keyUp('ctrl')
pyautogui.keyDown('alt')
pyautogui.press('tab')
pyautogui.keyUp('alt')
print("Welcome to dictionary lookup!")
print("Press F2 to lookup a word on www.dictionary.com")
word = ""
keyboard.add_hotkey('f2', lookup)
keyboard.add_hotkey('f1', switch_back)
while word is not "stop":
pass
Some of my other scripts that ask for input will not close immediately. The one I tried does not use any imports, so I'm theorizing this might have something to do with it. The reason I want this is that I want to be able to press windows button, type name of script and press enter. Rather than to find the folder, open a command window and type the whole thing out.
It seems the problem has been resolved. A time ago I tried installing a newer version of python (3.8). I have not been using this version (because I could not figure out how to change the python interpreter in Pycharm). I tried uninstalling it, and it seems to be working now.

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

This question already has answers here:
How to keep a Python script output window open?
(27 answers)
Closed 8 years ago.
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.")
You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.
However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.
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.
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
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.
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.
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

Categories