我目前有一个爬虫, 爬取的东西目测要好些天才能完
所以我设计成了能够自动续爬的形式, 不过我选择想再进一步
记录每次开始和结束的时间
但是不知道怎样在<ctrl-C>这种键盘终端的时候去写下程序退出的时间
望指点指点, 感觉是要捕获异常..
Ctrl+C 会产生KeyboardInterrupt异常,捕获它就可以了
try:
#要执行的代码
except KeyboardInterrupt, e:
print "Interrupt..."
那就捕信号吧,ctrl-c也是信号,SIGINT
man kill:
Some of the more commonly used signals:
1 HUP (hang up)
2 INT (interrupt)
3 QUIT (quit)
6 ABRT (abort)
9 KILL (non-catchable, non-ignorable kill)
14 ALRM (alarm clock)
15 TERM (software termination signal)
import time
import signal
def CtrlCHandler(signum, frame):
current_time = time.time()
sys.exit(0)
signal.signal(signal.SIGINT, CtrlCHandler)
Ctrl-C
或者 kill -2 pid
的时候都会到这个CtrlCHandler
.
建议用信号而不是KeyboardInterrupt
catch KeyboardInterrupt
import time
import datetime
print('stime:', datetime.datetime.now())
try:
while True:
time.sleep(1)
print('go')
except KeyboardInterrupt:
print('etime:', datetime.datetime.now())
測試:
stime: 2016-07-28 01:54:21.647561
go
go
go
<Ctrl+c>
etime: 2016-07-28 01:54:25.010312
我回答過的問題: Python-QA