일정한 간격 (기본값 1 초)으로 코드를 실행 하는 작은 스크립트 interruptableloop.py 가 있으며 실행중인 동안 화면에 메시지를 펌핑하고 CTL-C로 보낼 수있는 인터럽트 신호를 트랩합니다.
from interruptableLoop import InterruptableLoop
loop=InterruptableLoop(intervalSecs=1)
while loop.ShouldContinue():
pass
스크립트를 실행 한 다음 중단하면 다음 출력이 표시됩니다 (루프의 모든 패스에서주기가 펌핑 됨).
[py36]$ ./interruptexample.py
CTL-C to stop (or $kill -s SIGINT pid)
......^C
Exiting at 2018-07-28 14:58:40.359331
interruptableLoop.py :
"""
Use to create a permanent loop that can be stopped ...
... from same terminal where process was started and is running in foreground:
CTL-C
... from same user account but through a different terminal
$ kill -2 <pid>
or $ kill -s SIGINT <pid>
"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
def __init__(self,intervalSecs=1,printStatus=True):
self.intervalSecs=intervalSecs
self.shouldContinue=True
self.printStatus=printStatus
self.interrupted=False
if self.printStatus:
print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
signal.signal(signal.SIGINT, self._StopRunning)
signal.signal(signal.SIGQUIT, self._Abort)
signal.signal(signal.SIGTERM, self._Abort)
def _StopRunning(self, signal, frame):
self.shouldContinue = False
def _Abort(self, signal, frame):
raise
def ShouldContinue(self):
time.sleep(self.intervalSecs)
if self.shouldContinue and self.printStatus:
print( ".",end="",flush=True)
elif not self.shouldContinue and self.printStatus:
print ("Exiting at ",dtt.now())
return self.shouldContinue
time.sleep(5)
아래에 일부 코드를 들여 쓰기 만하면는 필요하지 않습니다while True:
(pass
최소한 만있을 수 있음 )