我有一个简单的 Python 脚本,它使用 Ctl-C 的信号处理程序。如果程序正常完成,则将结束时间传递给“print_results”函数。我希望 print_results 函数有一个可选参数,如果未传递,则只需获取当前的“现在”时间。但是当我从信号处理程序中调用它时,它没有得到正确的时间。
这是我的简化但可重现的程序:
import sys
import signal
import urllib2
import urllib
import datetime
import time
import getopt,sys
def signal_handler(signal, frame):
print_results()
sys.exit(0)
def print_results(ended=datetime.datetime.now()):
print "\nEnded at ",ended
print "Total time: ",(ended - startTime)
print "Finished ",numIterations," iterations, received ",totalRecords," records"
numIterations = 0
maxIterations = 8
delaySecs = 3
totalRecords = 0
# set up signal handler
signal.signal(signal.SIGINT, signal_handler)
startTime = datetime.datetime.now()
print "Starting at ",time.asctime(time.localtime())
while (numIterations < maxIterations):
iterStartTime = datetime.datetime.now()
numIterations += 1
print "Iteration: ",numIterations
# sleep if necessary
if delaySecs > 0:
time.sleep(delaySecs)
iterEndTime = datetime.datetime.now()
print "Iteration time: ",(iterEndTime - iterStartTime)
endTime = datetime.datetime.now()
print "Ended at ",time.asctime(time.localtime())
print "Total test time: ",(endTime - startTime)
print_results(endTime)
这是我键入 Ctl-C 时发生的情况
$ python test.py
Starting at Fri Jun 15 08:28:15 2012
Iteration: 1
Iteration time: 0:00:03.003101
Iteration: 2
Iteration time: 0:00:03.003105
Iteration: 3
^C
Ended at 2012-06-15 08:28:15.766496
Total time: -1 day, 23:59:59.999964
Finished 3 iterations, received 0 records
似乎当 print_results 在没有参数的情况下被调用时,“结束”值没有被正确解释为日期时间对象。但是由于 Python 没有办法进行转换(据我所知),我无法判断出什么问题。
提前致谢,
米奇