Can I have a running python script(under Windows)being paused in the middle by user , and resume again when user decides ?
There is a main manager program which gen
If it were unix I'd recommend signal, but here is a crude version that does what you ask.
import time
while True:
try:
time.sleep(1) # do something here
print '.',
except KeyboardInterrupt:
print '\nPausing... (Hit ENTER to continue, type quit to exit.)'
try:
response = raw_input()
if response == 'quit':
break
print 'Resuming...'
except KeyboardInterrupt:
print 'Resuming...'
continue
Use Ctrl+C to pause, and ENTER to resume. Ctrl+Break can probably be used as a harsh kill, but I don't have the key on this keyboard.
A more robust version could use select on a pipe/socket, or even threads.
You can make a simple workaround by creating a PAUSEFILE
. Your to-be-paused script may periodically check for existence (or content) of such file.
User's PAUSE
command can create (or fill with proper content) such file.
I have used this approach in a similar situation, where I wanted to be able to pause my Python scripts and resume them later. They contain something like
if os.path.isfile(PAUSEFILE):
raw_input('Remove ' + PAUSEFILE + ' and hit ENTER to continue')
in their main loops.
It is nasty and could be broken if the code really depended on it, but for the use cases, where the pause is done by users at random, I guess it will not matter.
The PAUSE
command is simply touch $PAUSEFILE
.
I don't understand very well your approach but every time a user needs to press a enter to continue the script you should use:
input() #for python 3k
raw_input() #for python 2k
without assigning the receiving answer to a variable.
If you're launching your python script from the windows command window, you can use msvcrt.kbhit() as a non-blocking key press check as implemented here: http://code.activestate.com/recipes/197140-key-press-detection-for-windows-text-only-console-/
I found so hacky those responses, while being interesting too.
The best approach is the https://stackoverflow.com/a/7184165/2480481 doing it using KeyboardInterrupt
exception.
As i noticed nobody mention "using a debugger", i'll do it.
Install pdb, Python debugger with pip install pdb
.
Follow that to make your script pausable https://stackoverflow.com/a/39478157/2480481 by Ctrl+c instead of exit it.
The main benefit of using a debugger (pdb) is that you can inspect the variables, values, etc. This is far way more powerfull than just pause/continue it.
Also, you can add Ipython interface with pdb attached to debug your app when crashes. Look at: https://stackoverflow.com/a/14881323/2480481
You can use Pdb
module in python.
Eventhough it's a debugger, in your case it helps you pass and continue wherever you have a breakpoint in the code.
Also when you resume you can get a glimpse of where it is paused and what are the values of the variables etc. Which will be very helpful.
python debugger - pdb