1

我想在退出时更改变量的值,以便在下一次运行时保持上次设置的值。这是我当前代码的简短版本:

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

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

4

2 回答 2

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)
于 2013-01-22T17:06:10.127 回答
0

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

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

希望能帮助到你!

于 2013-01-22T16:54:49.583 回答