让我们假设我们有一个用python编写的这样一个简单的守护进程:
def mainloop():
while True:
# 1. do
# 2. some
# 3. important
# 4. job
# 5. sleep
mainloop()
Run Code Online (Sandbox Code Playgroud)
然后我们使用start-stop-daemon
默认的send SIGTERM
(TERM
)信号进行守护--stop
.
我们假设当前执行的步骤是#2
.在这个时刻,我们正在发送TERM
信号.
会发生什么是执行立即终止.
我发现我可以处理信号事件,signal.signal(signal.SIGTERM, handler)
但问题是它仍然会中断当前执行并将控制传递给handler
.
所以,我的问题是-它可以不中断当前执行,但处理TERM
(?)在独立的线程信号,使我能够设置shutdown_flag = True
,使mainloop()
有机会停止正常?
在调试模式下,有没有办法在PyCharm IDE(3.1)中发送键盘中断事件?
为什么不像以下代码一样捕获CTRL-C?
MAXVAL = 10000
STEP_INTERVAL = 10
for i in range(1, MAXVAL, STEP_INTERVAL):
try:
print str(i)
except KeyboardInterrupt:
break
print "done"
Run Code Online (Sandbox Code Playgroud)
我的期望是 - 如果在程序运行时按下CTRL-C,KeyboardInterrupt
则应该离开循环.它不是.
对我做错的任何帮助?
我有一个函数a
执行一些任务,另一个函数b
是对某些事件的回调。每当发生事件时,b
都会调用function并且我想让它能够中断 function 的执行a
。这两个函数都在同一个类中声明。
Functiona
不应该调用 function b
。功能b
是完全独立的,它是对来自ROS:机器人操作系统的“用户面部检测”等外部事件的回调。
我需要的基本上是像 Ctrl+C 这样的东西,它可以从 Python 中调用,它只会中止目标函数而不是整个程序。
这可以在 Python 中完成吗?
我需要一种sleep()
可以中止的方法(如此处或此处所述).
我的方法是threading.Event.wait()
在指定的持续时间内超时:
def abortable_sleep(secs, abort_event):
abort_event.wait(timeout=secs)
abort_event.clear()
Run Code Online (Sandbox Code Playgroud)
在调用之后abortable_sleep(10, _abort)
我现在可以(从另一个线程)调用_event.set(_abort)
让它abortable_sleep()
在10秒之前终止.
例:
def sleeping_thread():
_start = time.perf_counter()
print("%f thread started" % (time.perf_counter() - _start))
abortable_sleep(5, _abort)
print("%f thread stopped" % (time.perf_counter() - _start))
if __name__ == '__main__':
_abort = threading.Event()
while True:
threading.Thread(target=sleeping_thread).start()
time.sleep(3)
_abort.set()
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
输出:
0.000001 thread started
3.002668 thread stopped
0.000002 thread started
3.003014 thread stopped
0.000001 thread started
3.002928 thread stopped
0.000001 thread started …
Run Code Online (Sandbox Code Playgroud) 在*nix python信令允许我在准备好之前停止睡眠.在Windows中是否有任何类似的机制 - 似乎所有方法最终只在睡眠后拦截代码?
代码示例:
from time import sleep
.. do something that will intercept the sleep
try:
sleep(60)
finally:
print 'how to get here under 60 seconds in windows?'
Run Code Online (Sandbox Code Playgroud)
类似的问题没有Windows的答案: 在python中断/中断time.sleep()
python ×6
daemon ×1
interrupt ×1
pycharm ×1
python-2.7 ×1
sigterm ×1
thread-sleep ×1
windows ×1