我想在退出时更改变量的值,以便在下次运行时,它仍然是上次设置的值。这是我当前代码的简短版本:
def example():
x = 1
while True:
x = x + 1
print x
在"键盘中断"上,我希望在 while 循环中设置的最后一个值是全局变量。下次运行代码时,该值应该是第 2 行中的"x"。可能吗?
这有点笨拙,但希望它能给你一个想法,你可以在当前的情况下更好地实现(如果你想持久化更健壮的数据结构,你应该使用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)
您可以将要保留的任何变量保存到文本文件中,然后在下次运行时将它们读回脚本中。
这是用于读取和写入文本文件的链接。http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
希望对您有所帮助!