有没有一种方法可以使用Pythoneval()
和/或exec()
在程序运行之间保持状态,而无需将数据写入文件或数据库。这是更具体的问题。我想编写一个程序,打印出一个数字,然后每次再次运行时都将自身加1,而不会在文件或数据库中保留任何变量。我在最近的一次采访中被问到了这个问题。任何帮助表示赞赏。
免责声明:我不建议这样做。在99.999%的时间内,最好将可序列化的信息存储在自己的文件中。
如果通过“不将数据写入文件”来表示“不将数据写入其自己的文件”,则可以打开正在运行的Python文件并就地重写数据:
import re
x = 0
print "The value of the variable x is: {}".format(x)
with open("test.py") as file:
data = file.read()
data = re.sub(r"x = (\d+)", "x = {}".format(x+1), data)
with open("test.py", "w") as file:
file.write(data)
现在,该值将随每次后续执行而更改。
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 0
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 1
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 2
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 3
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 4
但是同样,最好将数据保存在一个单独的文件中,例如shelve
:
import shelve
d = shelve.open("data.dat")
if "x" not in d:
d["x"] = 0
print "The value of x is: {}".format(d["x"])
d["x"] += 1
或者,如果您重视人类可读性,则可以使用json:
import json
try:
with open("data.dat") as file:
d = json.load(file)
except IOError: #first execution. file doesn't exist yet.
d = {"x":0}
print "The value of x is: {}".format(d["x"])
d["x"] += 1
with open("data.dat", "w") as file:
json.dump(d, file)
如果您有很多数据,甚至是功能完善的数据库。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句