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
6
  • 5
    Great! Now go ahead and implement it, if you face difficulties, then post your code with errors. Commented Feb 15, 2017 at 14:53
  • 3
    Why wouldn't you be able to do this? What have you tried? Commented Feb 15, 2017 at 14:53
  • I think you may be looking for a structured file format such as yaml or json that supports save/load of python variables? Commented Feb 15, 2017 at 14:57
  • 1
    Why don't you just import both of the scripts? Then you don't need to save anything. Commented Feb 15, 2017 at 14:58
  • 1
    Go take a look at the pickle module Commented Feb 15, 2017 at 15:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.