-1

I try to share a value between two python scripts, I set the value at the first script with a singleton,but when i get the value at the second script, the default value (0) is returned .

Here are my files: the file that gets the value:

import mod #import the singleton class

...

    def sendDistance(self):

        print(mod.getDistance()) #get the value

The file that sets the value:

 import mod #import the singleton class
 ...


    mod.setDistance(35) #set the value with the singleton file mod.py

The singleton file:(mod.py)

import distance #import the file where value is stored
def setDistance(val): #set Value function
    distance.x=val
def getDistance(): #get value function
    return distance.x

And the file, where the value is stored:(distance.py)

x=0 #the default value that should be modified from mod

If I try to get the value at the file that sets the value (do a print(mod.getValue()) ), then the value is shown correctly. But at the getter side the value is always 0.

aphi
  • 41
  • 4

1 Answers1

0

Setting the distance only sets it in that running instance of Python. You could of course re-write distance.py with the new value. But that would only affect other scripts when they import that module.

If you want to share data between scripts that run at different times but on the same machine, just write that data into a file. Use an easily parsed format like JSON.

Sharing data between different scripts that run at the same time at the same time is more involved. The easiest way would be to for one script to start the other. Then you can use the communication features of the multiprocessing module.

For sharing data between scripts potentially running on different machines, you could use the socket module.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • I've already tried the solution with the file but it slows down any other process. How to make a multiprocessing function? In which way can the files communicate then? Thanks for your answer! – aphi Feb 18 '17 at 17:10
  • And the Variable has to be "live", so that it does not have a delay. Is there a possibility to get the variable directly from the other file? With import or so? – aphi Feb 18 '17 at 17:22
  • Import merely loads the content of the module it finds on disk. – Roland Smith Feb 18 '17 at 18:23
  • As for multiprocessing; read the documentation and the examples included therein. – Roland Smith Feb 18 '17 at 18:24