Let’s imagine i have a program in Python like this one (first.py):
GLOBALVAR = "pineapple"
def changeVAR(newValue):
global GLOBALVAR
GLOBALVAR = newValue
while(True):
print GLOBALVAR
And i want to chante the global variable GLOBALVAR with another python program while the first is running. For instance (second.py):
from second import changeVAR
#do something
first.changeVAR("banana")
Is it possible to do something like this? Meaning, to change a global variable of a running program with another program?
Thank you in advance!
What you describe (programs sharing the same variables) is only possible between different threads (which share the same python interpreter and data), not between different processes.
Modern operating systems do not allow a program to access the memory of another program. So you cannot just reach into the memory of another process and change something there. Allowing that would create all sorts of bugs and security problems.
It is possible to communicate with another program, using interprocess communication. This can be done with e.g. sockets, memory mapped files or writing to each other’s standard in- and output. There is also support for semaphores, shared memoy and message queues on UNIX-like operating systems.
The
multiprocessingmodule provides theQueueandPipeobjects to allow related processed to talk to each other.