我想在退出时更改变量的值,以便在下次运行时保持上次设置的值。这是我当前的代码很短的版本:Python - 在下一个会话退出时更改变量值
def example():
x = 1
while True:
x = x + 1
print x
在“一个KeyboardInterrupt”,我想在while循环设置的最后一个值是一个全局变量。在下次运行代码时,该值应该是第2行中的'x'。可能吗?
我想在退出时更改变量的值,以便在下次运行时保持上次设置的值。这是我当前的代码很短的版本:Python - 在下一个会话退出时更改变量值
def example():
x = 1
while True:
x = x + 1
print x
在“一个KeyboardInterrupt”,我想在while循环设置的最后一个值是一个全局变量。在下次运行代码时,该值应该是第2行中的'x'。可能吗?
这是一个有点哈克,但希望它给你的想法,你可以在你目前的情况更好地贯彻落实(pickle
/cPickle
是,如果你想坚持更强大的数据结构,你应该使用什么 - 这只是一个简单的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)
感谢RocketDokey,我得到了它的工作。没有想到我可以做到这一点。谢谢。 – sam
@SamGlider没问题,祝你好运:) – RocketDonkey
您可以将任何想要保留的变量保存到文本文件中,然后在下次运行时将它们读回到脚本中。
这里是读写文本文件的链接。 http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
希望它有帮助!
Thanks man。链接帮助。 – sam
为什么不只是在全局范围内声明x在函数之外? – Bharat
或者如果你的意思是在程序结束后应该保留x的值,那么你可以序列化它。请参阅http://docs.python.org/2/library/pickle.html – Bharat
在while循环结尾添加** open('myvar','w')。write(x)**,部分由RocketDonkey,并设置** x = open('myvar','r')。read()** on line 2. – sam