Write to File after Program Closes

时间:2015-07-28 16:49:18

标签: python multithreading if-statement system

This might sound like a really dulled down question but I have honestly searched everywhere for it but is there a way where once the user clicks the "exit" or "stop" button to stop there program right after you click that it will write data to a file somewhere? or would that be impossible since you closesd that program? I honestly don't know, Here's my try at it Its nothing really because I don't entirely know how to do it, but I just say this

if (onExit):
    f = open('file.txt', mode='w')
    f.write (data)
    f.close

my onExit is just a Boolean and yeah I'm just not sure how to do it, I know how dumb that code looks btw I just didn't know how to show to you guys that I have tried looking for it other then if I showed you my history tab

2 个答案:

答案 0 :(得分:1)

Clicking an 'exit' button typically does not actually close a program immediately. Instead, the code that runs when that button is pushed also takes care of saving data.

If we are talking about a console application, which is 'closed' by ctrl-c (i.e. a KeyboardInterrupt), you can use a try-except block:

try:
    raw_input()
except KeyboardInterrupt:
    # save here
    raise

Python does support atexit handlers, but they are most likely not the right solution to your problem.

答案 1 :(得分:0)

如果您在Eclipse上使用PyDev,则终止按钮(红色方块)会向系统发送一条终止消息,这反过来会在不执行其他代码的情况下终止您的程序。

正如之前的回答所说,你可以使用atexit模块,但只有在程序正常结束时才能使用。

另请参阅:Is it possible for Eclipse to terminate gently instead of using SIGKILL?