gpt4 book ai didi

python - 要求 python 从 bash (/tmp/stop?) 停止(控制)的有效方法

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:39 24 4
gpt4 key购买 nike

从 Bash 脚本请求 Python 程序停止(以受控方式)的最有效方式是什么(就轮询开销而言)。在 python 方面,我想要一个函数(尽可能快地执行),它在请求停止时返回 true,否则返回 false。如果为真,我们保存我们的工作,释放资源并退出。

对于一些简单的工具,我实现了以下内容:

  • 在 bash 中我做了一个touch/tmp/stop
  • 我的 Python 程序经常轮询 /tmp/stop 确实存在。如果它存在,则以受控方式退出。
  • 我的 bash 脚本等待(循环 - sleep - ps)直到相关进程停止。

此解决方案有效,但轮询此文件很可能不是最有效的方法。

是否有其他开销较小的选项(就 Python 轮询时间而言)?

最佳答案

您可以向 python 进程发送中断信号 (SIGINT)。这与您按下 Ctrl+C 时 shell 发送的信号相同:

在 Bash 中看起来像这样:

python my_script.py &         # start the script in background
pyscript_pid=$! # store the python interpreter' PID
sleep(5) # pause 5 seconds
kill -s SIGINT $pyscript_pid # send the SIGINT signal to the process

在 Python 中,您只需捕获解释器接收到 SIGINT 信号时抛出的 KeyboardInterrupt 异常:

try:
print ("I'm still running...")
# do something useful, but it must be interruptible at any time!

except KeyboardInterrupt:
print ("I'm going to quit now.")

# tidy up...
# ... and exit

虽然在 try block 中被中断时,你不应该做会破坏任何东西的事情,只执行可以被中断或重置为整理代码中最后有效状态的事情。或者,您可以使用 try: ... finally: ... 来确保 finally block 中的代码将始终启动,即使 try 中的代码 在运行时被打断。

您还可以查看 How do I capture SIGINT in Python?或 @Robᵩ 的答案,以找出如何捕获所有可能的信号而不仅仅是 SIGINT 以及如何为它们注册事件处理程序而不是使用 try-catch(-finally),但这是最简单的方法。

关于python - 要求 python 从 bash (/tmp/stop?) 停止(控制)的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com