[英]How to stop/terminate a python script from running? (once again)
Context :上下文:
I have a running python script.我有一个正在运行的 python 脚本。 It contains many os.system("./executableNane")
calls in a loop.它在循环中包含许多os.system("./executableNane")
调用。
If I press ctrl + C , it just stops the execution of the current ./executableNane
and passes to the next one.如果我按ctrl + C ,它只会停止当前./executableNane
的执行并传递到下一个。
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
).请注意,我已经仔细阅读了此处的问题/答案,但即使使用kill
我也可以杀死可执行的可执行文件Nane但不能杀死整个脚本(我无法使用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.我必须停止脚本(无需重新启动系统)的唯一方法是继续按 ctrl + C 循环,直到所有测试完成。
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.您还可以使用subprocess
通过subprocess.PIPE
接收和发送信息,您可以在文档中阅读更多信息。
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.与我找到的解决方案相比,该问题的另一个解决方案(由@Quillan Kaseman 提供)要优雅得多。 All my problems are solved when I press Ctrl + Z instead of Ctrl + C .当我按Ctrl + Z而不是Ctrl + C时,我所有的问题都解决了。
Indeed, I have no idea why with Z
works and with C
does not.事实上,我不知道为什么Z
可以工作而C
不行。 (I will try to look for some details later on). (我稍后会尝试寻找一些细节)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.