Share a dict with multiple Python scripts

后端 未结 8 1162
予麋鹿
予麋鹿 2020-12-14 11:31

I\'d like a unique dict (key/value) database to be accessible from multiple Python scripts running at the same time.

If script1.py updates

8条回答
  •  一向
    一向 (楼主)
    2020-12-14 12:01

    You can use python dictionary for this purpose.

    Create a generic class or script named as G, that initializes a dictionary in it. The G will run the script1.py & script2.py and passes the dictionary to both scripts file, in python dictionary is passed by reference by default. In this way, a single dictionary will be used to store data and both scripts can modify dictionary values, changes can be seen in both of the scripts. I hope script1.py and script2.py are class based. It doesn't guarantee the persistence of data. For persistence, you can store the data in the database after x intervals.

    Example

    script1.py

    class SCRIPT1:
    
        def __init__(self, dictionary):
            self.dictionary = dictionary
            self.dictionary.update({"a":"a"})
            print("SCRIPT1 : ", self.dictionary)
    
        def update(self):
            self.dictionary.update({"c":"c"})          
    

    script2.py

    class SCRIPT2:
        def __init__(self, dictionary):
            self.dictionary = dictionary
            self.dictionary.update({"b":"b"})
            print("SCRIPT 2 : " , self.dictionary)
    

    main_script.py

    import script1
    import script2
    
    x = {}
    
    obj1 = script1.SCRIPT1(x) # output: SCRIPT1 :  {'a': 'a'}
    obj2 = script2.SCRIPT2(x) # output: SCRIPT 2 :  {'a': 'a', 'b': 'b'}
    obj1.update()
    print("SCRIPT 1 dict: ", obj1.dictionary) # output: SCRIPT 1 dict:  {'c': 'c', 'a': 'a', 'b': 'b'}
    
    print("SCRIPT 2 dict: ", obj2.dictionary) # output: SCRIPT 2 dict:  {'c': 'c', 'a': 'a', 'b': 'b'}
    

    Also create an empty _ init _.py file in the directory where you will run the scripts.

    Another option is:

    Redis

提交回复
热议问题