1

Context:

I have a running python script. It contains many os.system("./executableNane") calls in a loop.

If I press ctrl + C, it just stops the execution of the current ./executableNane and passes to the next one.

Question:

How to stop the execution of the whole script and not only the execution of the current executable called?

Please note that I have read carefully the question/answer here but even with kill I can kill the executable executableNane but not the whole script (that I cannot find using top).

The only way I have to stop the script (without reboot the system) is to continue to press ctrl + C in a loop as well until all the tests are completed.

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Leos313
  • 5,152
  • 6
  • 40
  • 69

2 Answers2

1

You can use subprocess and signal handlers to do this. You can also use subprocess to receive and send information via subprocess.PIPE, which you can read more about in the documentation.

The following should be a basic example of what you are looking to do:

import subprocess
import signal
import sys

def signal_handler(sig, frame):
    print("You pressed Ctrl+C, stopping.")
    print("Signal: {}".format(sig))
    print("Frame: {}".format(frame))

    sys.exit(123)

# Set up signal handler
signal.signal(signal.SIGINT, signal_handler)

print("Starting.")
while True:
    cmd = ['sleep', '10']
    p = subprocess.Popen(cmd)
    p.wait()
    if p.returncode != 0:
        print("Command failed.")
    else:
        print("Command worked.")
  • +1 I will try the solution as soon I will come back to the yestarday problem on the other project I am working on! – Leos313 Dec 18 '19 at 09:20
  • @Leos313 I can't comment on your answer due to rep, but `Ctrl-Z` pauses the execution of your program rather than stops it. Because `os.system()` is a blocking call, your Python process is waiting for the `executableName` process to finish. You are suspending the currently running `executableName` process so your Python process is still waiting for it to finish. If you resume the process with `bg` or `fg` the process will resume exactly where you left off. Keep in mind that no cleanup will have happened with Ctrl-Z because the process hasn't exited (files still open, etc...). – Quillan Kaseman Dec 19 '19 at 17:10
0

The other solution to the question (by @Quillan Kaseman) is much more elegant compared with the solution I have found. All my problems are solved when I press Ctrl + Z instead of Ctrl + C.

Indeed, I have no idea why with Z works and with C does not. (I will try to look for some details later on).

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Leos313
  • 5,152
  • 6
  • 40
  • 69