Python - 在退出时为下一个会话更改变量值

时间:2013-01-22 16:47:47

标签: variables python-2.7 keyboardinterrupt

我想在退出时更改变量的值,以便在下次运行时,它仍然是最后设置的值。这是我当前代码的简短版本:

def example():
    x = 1
    while True:
        x = x + 1
        print x

在'KeyboardInterrupt'上,我希望while循环中设置的最后一个值是一个全局变量。在下次运行代码时,该值应为第2行中的“x”。是否可能?

2 个答案:

答案 0 :(得分:0)

您可以将要保留的任何变量保存到文本文件中,然后在下次运行时将其读回脚本。

这是一个用于读取和写入文本文件的链接。 http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

希望它有所帮助!

答案 1 :(得分:0)

这有点hacky,但希望它能让您了解在当前情况下可以更好地实现(pickle / cPickle是您应该使用的内容,如果您想要保留更强大的数据结构 - 这只是一个简单的例子):

import sys


def example():
    x = 1
    # Wrap in a try/except loop to catch the interrupt
    try:
        while True:
            x = x + 1
            print x
    except KeyboardInterrupt:
        # On interrupt, write to a simple file and exit
        with open('myvar', 'w') as f:
            f.write(str(x))
            sys.exit(0)

# Not sure of your implementation (probably not this :) ), but
# prompt to run the function
resp = raw_input('Run example (y/n)? ')
if resp.lower() == 'y':
    example()
else:
  # If the function isn't to be run, read the variable
  # Note that this will fail if you haven't already written
  # it, so you will have to make adjustments if necessary
  with open('myvar', 'r') as f:
      myvar = f.read()

  print int(myvar)