試試看吧自己:
這工作(如果被執行的代碼你的機器上過快的for
循環迭代增加一個零):
a = 0
try:
for i in range(1000000):
a = a + 1
except (KeyboardInterrupt, SystemExit):
print a
raise
print a
這不起作用,因爲數據保存在中間的文件中。 try
塊不撤消將數據保存到文件。
a = 0
try:
for i in range(1000000):
if a == 100:
with open("d:/temp/python.txt", "w") as file:
file.write(str(a))
a = a + 1
except (KeyboardInterrupt, SystemExit):
raise
This Works。數據僅在最後保存。
a = 0
try:
for i in range(1000000):
a = a + 1
except (KeyboardInterrupt, SystemExit):
raise
with open("d:/temp/python.txt", "w") as file:
file.write(str(a))
因此準備try
塊內的信息,並保存之後。
另一種可能性:使用原始數據保存臨時備份文件,並將備份文件重命名爲except塊中的原始文件名。
您需要捕獲^ C處理程序並執行關閉功能來處理它。 –
你可以發佈它作爲答案,並描述你的意思。 –
http://stackoverflow.com/questions/4205317/capture-keyboardinterrupt-in-python-without-try-except這裏有一種方法來處理它:)只是搜索了一下 –