How to share common data among multiple Python files?

PythonServer Side ProgrammingProgramming

You're not going to be able to share common data between multiple Python files without storing the information somewhere external to the two instances of the interpreter. Either you have to use a networking/socket setup - or you have to use temporary files. The easiest way is to use a file to share the data. You can use the pickle module to store objects to file from one script and use another script to open that file and deserialize the file as an object. For example,

In the file you want to write the object from −
import pickle
shared = {"Foo":"Bar", "Parrot":"Dead"}
fp = open("shared.pkl","w")
pickle.dump(shared, fp)

In the file where you want to consume this object −
import pickle
fp = open("shared.pkl")
shared = pickle.load(fp)
print shared["Foo"]
Published on 27-Dec-2017 11:07:26