我正在一个我希望让脚本在一夜之间运行的环境中工作,但出于政策原因,不能假设PC将保持通电状态(在任意时间段后以不合适的方式自动关闭)。
我有一个写入文本文件的python脚本。在测试期间,当我在某些情况下不合理地终止程序时,一行文本将仅部分写入文件。我也在使用csv模块。
在这里尝试近似代码:
import csv
outCSV = open("filename.txt", "a")
#more code here for writing multiline non CSV "header" block if file doesn't already exist
csvWriter = csv.writer(outCSV,lineterminator='\n')
#loop through a list, using values to derive other data for writing out later
lookupList = range(5)
for row in lookupList:
#function to return list of data elements from web source for CSV writer, using range(100) for mock data
outDataRow = range(100)
csvWriter.writerow(outDataRow)
#save after each row in case script is closed aburptly
outCSV.flush()
print "done!"
我意识到上面的例子是微不足道的,它可能运行得太快而无法可靠地关闭脚本,因此csvWriter.writerow()无法完成写出一行。实际项目涉及检查一些基于Web的内容,其中每个URL最多需要15秒才能加载,然后可能将数百个项目写入一行。寻找更多概念性答案(我怀疑问题是当“csvWriter.writerow(outDataRow)”仍在执行并且程序关闭时)。
到目前为止,我所拥有的最好的想法是构建一个错误检查器来检查任何输出(一旦我重新启动第二天),查找不完整的记录并重做这些行。想知道是否有更聪明的方法?
P.S。我尝试过搜索,但即使选择有效的关键字也很困难,原谅如果这是重复的问题(添加用于在评论中找到它的关键字?)
答案 0 :(得分:0)
我认为你应该看signal module。这是与您案件有关的简要说明。
当操作系统重新启动时,它首先向所有程序发送信号。这是告诉程序"请关闭!!"。程序负责清理和关闭。信号也用于其他事情,但这与你有关。
在python(和其他)中,我们编写了一个处理信号的函数,即在收到信号时清理和退出。信号处理在python中完成:
import signal #you need this to handle signals
import time #used in this simple example
#open a file
f = open ('textfile.txt', 'w')
#signal handler. it has two parameters
#signum: signal number. there are many signals each with its number
#frame: i am not really sure what this is but i guess it is used for
# things i do not need. just a guess though
def sig_handler (signum, frame):
#print debugging information
print ('got', signum, 'signal, closing file...')
#close the file before exiting
f.close()
print ('exiting')
#exit. you have to write this to end the program from here
exit (1)
#create signal handler
#when `SIGTERM` signal is received, call function `sig_handler`
#if program receive the signal without creating a handler for it, the program
#will terminate without any clean up
signal.signal (signal.SIGTERM, sig_handler)
#infinite loop. will never end unless a signal is received to stop the program
while True:
#write to file
print ('test line', file=f)
#delay to simulate slow writing to file
time.sleep (1)
您应该知道操作系统关闭时发送的信号,或者只是使用相同的处理程序处理所有可能的信号。我认为SIGTERM是用于在关闭期间终止进程的那个,但我不确定。
有一个你永远无法处理的信号,你的程序将被强制关闭而不进行任何清理(我确信在unix中。它可能存在于windows中)。但是在极少数情况下会发送一个(例如,程序挂起并且在SIGTERM或其他信号发送后不会关闭)。
希望这会有所帮助...