Python Forum

Full Version: Is it Possible to pause a script?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
I was wondering if it is possible to pause a Python script when it is running.
Ctrl+C aborts a script,
Is there anything I can do to pause it?

Thank you.
(Mar-31-2023, 09:58 PM)tester_V Wrote: [ -> ]Is there anything I can do to pause it?
Yes, there is a way. In Unix/Linux there is a rich number of signals you can send to a process. I am not sure what is implemented of it in Windows.
I understand you run your program from the terminal/dosbox, for you say you do a <Ctrl>C. This sends the signal SIGINT (Interrupt) to the process. You can catch those signals. Read all about it in "signal — Set handlers for asynchronous events".
Example:
#! /usr/bin/env python3
import signal
import time

def handler(signum, frame):
    input("Progam paused. Hit enter to resume")
    return

signal.signal(signal.SIGINT, handler)

for i in range(10):
    print(i)
    time.sleep(1)
Output:
$ ./signalexample.py 0 1 2 ^CProgam paused. Hit enter to resume 3 4 5 6 ^CProgam paused. Hit enter to resume 7 8 9
Outstanding!
ibreeden, thank you very much!
Pause a process: CTRL + Z
Continue the process: fg
(Apr-03-2023, 01:21 PM)DeaD_EyE Wrote: [ -> ]Pause a process: CTRL + Z
Continue the process: fg

No words! You are Da Man Wink and I'm probably confused but CTRL+Z does not work...
What does it mean "Continue the process: fg" ?

Thank you
(Apr-05-2023, 05:50 AM)tester_V Wrote: [ -> ]I'm probably confused but CTRL+Z does not work...
It works if you start the program from the linux terminal and then type ^Z in the terminal.

If you want to do the same outside the terminal, you could perhaps send SIGTSTP to the process to pause it and then SIGCONT to resume it.
I see.
Thank you!
You guys are awesome!