简体   繁体   中英

How to stop/terminate a python script from running? (once again)

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.

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.")

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM