Correct way to pause a Python program - python

I've been using the input function as a way to pause my scripts:
print("something")
wait = input("Press Enter to continue.")
print("something")
Is there a formal way to do this?

It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")

For Windows only, use:
import os
os.system("pause")

So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:
import os
import system
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
print("Think about what you ate for dinner last night...")
pause()
Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.
NOTE: For Python 3, you will need to use input as opposed to raw_input

I assume you want to pause without input.
Use:
time.sleep(seconds)

I have had a similar question and I was using signal:
import signal
def signal_handler(signal_number, frame):
print "Proceed ..."
signal.signal(signal.SIGINT, signal_handler)
signal.pause()
So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.

I use the following for Python 2 and Python 3 to pause code execution until user presses Enter
import six
if six.PY2:
raw_input("Press the <Enter> key to continue...")
else:
input("Press the <Enter> key to continue...")

print ("This is how you pause")
input()

As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:
Python 3.x:
input('Press <ENTER> to continue')
Python 2.x:
raw_input('Press <ENTER> to continue')
For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on
Python 2.x) to prompt the user, rather than a time delay. Fast readers
won't want to wait for a delay, slow readers might want more time on
the delay, someone might be interrupted while reading it and want a
lot more time, etc. Also, if someone uses the program a lot, he/she
may become used to how it works and not need to even read the long
text. It's just friendlier to let the user control how long the block
of text is displayed for reading.
Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard :)

Very simple:
raw_input("Press Enter to continue ...")
print("Doing something...")

By this method, you can resume your program just by pressing any specified key you've specified that:
import keyboard
while True:
key = keyboard.read_key()
if key == 'space': # You can put any key you like instead of 'space'
break
The same method, but in another way:
import keyboard
while True:
if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space'
break
Note: you can install the keyboard module simply by writing this in you shell or cmd:
pip install keyboard

cross-platform way; works everywhere
import os, sys
if sys.platform == 'win32':
os.system('pause')
else:
input('Press any key to continue...')

I work with non-programmers who like a simple solution:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:
Paused. Press ^D (Ctrl+D) to continue.
>>>
The Python Debugger is also a good way to pause.
import pdb
pdb.set_trace() # Python 2
or
breakpoint() # Python 3

I think I like this solution:
import getpass
getpass.getpass("Press Enter to Continue")
It hides whatever the user types in, which helps clarify that input is not used here.
But be mindful on the OS X platform. It displays a key which may be confusing.
Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?

user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke).
By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer.
import readchar
readchar.readkey()

For cross Python 2/3 compatibility, you can use input via the six library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )

I think that the best way to stop the execution is the time.sleep() function.
If you need to suspend the execution only in certain cases you can simply implement an if statement like this:
if somethinghappen:
time.sleep(seconds)
You can leave the else branch empty.

Related

Why msvcrt.getch() is getting always same input without pressing any key on Windows

I am using Windows. I want take user input without pressing enter key and I found many examples, but somehow they are not working on me. I do not press any key and still msvcrt.getch() function is getting input(or atleast it is printing something) all the time. My code below:
import msvcrt
from time import sleep
while True:
print(msvcrt.getch())
sleep(1)
This is printing b'\xff' all the time. And if I press something, it does not care, it still print same string. I am using python 3.6
Problem solved. If using msvcrt: Code has to run in console. I was running that with IDLE.
https://www.reddit.com/r/learnpython/comments/3ji6ew/ordgetch_returns_255_constantly/
Thanks to ingolemo.

Ignore keyboard input in python while sleeping

I'm having a code with a loop asking for some input and then sleeps for some time. The purpose is to prevent for human errors, forcing the user to wait before entering the next input.
The problem is, that python does not ignore the keyboard inputs while time.sleep.
Here is an example code:
from time import sleep
from msvcrt import getch
for i in range(3):
print 'Enter a character'
char = getch()
sleep(2)
print char
When pressing some characters consecutively during time.sleep(), msvcrt.getch() remembers them and the loop runs to the end. I want that every character pressed during sleep will be ignored. How can I do that?
Sorry for wrong answer that i have posted before(as i have deleted though), it is the human level problem that you are asking for.
The program thread is the only event that is put on to sleep, while the keyboard process is still running obviously it will record all the inputs and type after resuming from sleep.
This can't be achieved in this fashion
This is an OS dependant issue, for windows i use this:
import msvcrt
import time
time.sleep(4)
while msvcrt.kbhit():
flush = input()
entry = input("Press enter!")
it just catches all the inputs before asking user for a new input, hope it helps!

Python: detect specific key press and prompt the user

I need to print out sentence "Hello World" every 10 seconds. However, if the user either 'c' or 'Enter', the program should stop printing the sentence and prompt the user to provide with the another sentence. The user-provided sentence is checked and if the sentence contains any digits, a message shows up: "cannot contain digits". Otherwise a message shows up: "correct sentence". After displaying either of the messages, the program continues printing "Hello World".
Here is the code I have strated with. Any hints on how to continue further would be greatly appreciated.
Thanks!
import threading
def looping():
threading.Timer(10.0, looping).start()
print("Hello World!")
looping()
From my understanding of your assignment's instructions, it looks like you're on the right track with using a timer to print "Hello World"! I'd like to upvote Irmen de Jong's comment on your question with regard to the statement "threads and console input/output don't work nicely together", since I've experienced this myself in C programming.
Once you have the timer going, the text it prints to the screen shouldn't have an effect on responding to keyboard input. If it's really required to respond directly to a keypress of 'c' (not followed by 'Enter', as one would normally have to do when reading input from the keyboard with input()), I recommend following one of the solutions in Python method for reading keypress? to figure out how you would like to implement that.
EDIT: Implementing a solution using a thread-based timer is a bit more tricky than I thought.
As you may have found in your research on this problem, the threading.Timer object has both start() and stop() methods that you can use to control the execution of individual thread timers if you've saved a reference to the timer in a variable (e.g. doing my_timer = threading.Timer(10.0, looping) then calling my_timer.start() to start the timer). If you do this, you may be able to call my_timer.stop() to pause the looping, provided you've kept a proper reference to the current timer instance that you need to stop at that point in time.
To make things a bit easier, I chose to create a global variable PAUSE_LOOPING that, when set to False, will stop a new timer instance from being started when looping is called, thereby halting all further repetitions of the function until PAUSE_LOOPING is set back to True and looping() is called again:
import threading
from msvcrt import getch
PAUSE_LOOPING = False
def looping():
global PAUSE_LOOPING
if not PAUSE_LOOPING:
threading.Timer(10.0, looping).start()
print("Hello World!")
looping()
while True:
# key = ord(getch())
# if key == 13: # Enter
# PAUSE_LOOPING = True
input_string = input()
if input_string == "":
PAUSE_LOOPING = True
else:
PAUSE_LOOPING = False
looping()
Commented out in the last code block is one way to grab a key press directly (without needing to press the 'Enter' key as is required by input()) taken from the stackoverflow question I linked to earlier in my answer. This should work as long as you're using Python for Windows (so you have the MS VC++ runtime library msvcrt installed), but to make the script stop when pressing 'Enter' you can use the standard input() function. In my example, typing any other string of characters before pressing 'Enter' will resume looping after it's been paused.
NOTE: Beware of using Python's IDLE to run this code. It won't work. Instead, you must run it from the command line.

Python - detect keypress in shell

Trying to detect and respond to key presses in Python. Am using IDLE and Python 3.3. I have the following code so far
import msvcrt
while True:
inp = ord(msvcrt.getch())
if (inp != 255):
print(inp)
I have the IF statement because if I just allow the script to throw out the value of 'inp' it just spoons out 255 repeatedly. So I threw in the if statement to respond to anything but 255 and now when run the code does nothing but output the actual keypress character in the shell.
This is because getch reads the input immediately, it doesn't wait until you type something. When it doesn't receive any input, it will simply return "\xff" (ordinal 255).
The getch function is designed to work in a console, not in a graphical program.
When you use it in a graphical program it is going to return immediately with \xff.
If you run your program in the reguler python interpreter it will not cause you that problem.
In addition, when you run the loop with the if statement it is running continuously and using a lot more processor time then it needs. In windows the only proper way of doing so is using window messages which sounds like it is overkill for your needs.
Python has a keyboard module with many features. You Can Use It In Both Shell and Console. It Also Detect Key For The Whole Windows.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('a'): #if key 'a' is pressed
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'): # and so on
#then do this
When You Install The Module, got to folder:
python36-32/Lib/site-packages/keyboard
Open File_keyboard_event.py in notepad++.
There will be keyboard events.
Not Sure About All Of Them.
Thanks.

Python: How to quit CLI when stuck in blocking raw_input?

I have a GUI program which should also be controllable via CLI (for monitoring). The CLI is implemented in a while loop using raw_input.
If I quit the program via a GUI close button, it hangs in raw_input and does not quit until it gets an input.
How can I immediately abort raw_input without entering an input?
I run it on WinXP but I want it to be platform independent, it should also work within Eclipse since it is a developer tool. Python version is 2.6.
I searched stackoverflow for hours and I know there are many answers to that topic, but is there really no platform independent solution to have a non-blocking CLI reader?
If not, what would be the best way to overcome this problem?
Thanks
That's not maybe the best solution but you could use the thread module which has a function thread.interrupt_main(). So can run two thread : one with your raw_input method and one which can give the interruption signal. The upper level thread raise a KeyboardInterrupt exception.
import thread
import time
def main():
try:
m = thread.start_new_thread(killable_input, tuple())
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
print "exception"
def killable_input():
w = thread.start_new_thread(normal_input, tuple())
i = thread.start_new_thread(wait_sometime, tuple())
def normal_input():
s = raw_input("input:")
def wait_sometime():
time.sleep(4) # or any other condition to kill the thread
print "too slow, killing imput"
thread.interrupt_main()
if __name__ == '__main__':
main()
Depending on what GUI toolkit you're using, find a way to hook up an event listener to the close window action and make it call win32api.TerminateProcess(-1, 0).
For reference, on Linux calling sys.exit() works.

Categories