문제

I want to change the value of a variable on exit so that on the next run, it remains what was last set. This is a short version of my current code:

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

On 'KeyboardInterrupt', I want the last value set in the while loop to be a global variable. On running the code next time, that value should be the 'x' in line 2. Is it possible?

도움이 되었습니까?

해결책

This is a bit hacky, but hopefully it gives you an idea that you can better implement in your current situation (pickle/cPickle is what you should use if you want to persist more robust data structures - this is just a simple case):

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)

다른 팁

You could save any variables that you want to persist to a text file then read them back in to the script the next time it runs.

Here is a link for reading and writing to text files. http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

Hope it helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top