我的问题是关于在Python中保存变量的值。更具体地说,我有两个不同的脚本,用两种不同的方式计算相同的东西。我想要做的是比较从两个脚本返回的变量的值。所以我想知道我是否可以运行第一个脚本,保存我的一个变量的值(比如一个矩阵V),然后运行第二个脚本并比较第二个脚本计算的同一个变量的值。
答案 0 :(得分:2)
就像@claymore在评论中所说,这可以用泡菜来完成。您将每个变量存储到pickle中,然后从比较脚本中获取pickle对象。
下面是一个例子
<强> script_a.py 强>
# Save a dictionary into a pickle file.
import pickle
def funca():
favorite_color = { "lion": "yellow", "kitty": "red" }
with open("a.pickle","wb") as f:
pickle.dump( favorite_color, f)
funca()
<强> script_b.py 强>
# Save a dictionary into a pickle file.
import pickle
def funcb():
favorite_color = { "lion": "blue", "kitty": "orange" }
with open("b.pickle","wb") as f:
pickle.dump( favorite_color, f)
funcb()
<强> compare.py 强>
# Load the dictionary back from the pickle file.
import pickle
import os
os.system("python script_a.py")
os.system("python script_b.py")
a_fav = pickle.load(open( "a.pickle", "rb" ))
b_fav = pickle.load(open( "b.pickle", "rb" ))
print "script 1 had favorite = ", a_fav
print "script 2 had favorite = ", b_fav