Change language

How do I share shared data between multiple Python files?

|

You cannot exchange shared data between multiple Python files without storing the information somewhere outside of the two interpreter instances. Either you need to use the network / socket setup or use temporary files. 

The easiest way &use the file to exchange data. You can use the pickle module to store objects to a file from one script and use another script to open that file and deserialize the file as an object. For example,



In the file from which you want to write an object &



 producer .py: import pickle shared = {"Foo": "Bar", "Parrot": "Dead"} fp = open ("shared.pkl", "w") pickle.dump (shared, fp) 

In the file where you want to use ь this object &

 consumer.py: im port pickle fp = open ("shared.pkl") shared = pickle.load (fp) print shared ["Foo"]