1

My question is regarding saving values of variables in Python. More specifically I have two different scripts that calculate the same things with 2 different ways. What I want to do is to compare the values of the variables returned from the two scripts. So I was wondering if I can run the first script, save the values of one of my variables (let say a matrix V) and then run the second script and compare the values for the same variable as they are calculated by the second script.

  • List item
Andriana
  • 367
  • 3
  • 8
  • 17

1 Answers1

3

Like @claymore said in the comments, this can be done with pickle. You store the variable you want from each into a pickle and then grab the pickle objects from the comparison script.

An example is below

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

source: https://wiki.python.org/moin/UsingPickle