Reputation: 5647
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.
Upvotes: 1
Views: 908
Reputation: 5647
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).
Upvotes: 0
Reputation: 98
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.")
Upvotes: 1