I have a Python script using the multiprocessing and sacn library:
from multiprocessing import Process
import time
import sacn
def GettingDMXValues():
while True:
receiver = sacn.sACNreceiver(bind_address = "***.**.**.**")
receiver.start()
@receiver.listen_on('universe', universe=1)
def callback(packet):
#print(packet.dmxData)
global DMXValues
DMXValues = packet.dmxData
print(DMXValues)
receiver.join_multicast(1)
time.sleep(10)
receiver.leave_multicast(1)
receiver.stop()
def printtest2():
while True:
print(DMXValues)
p1 = Process(target=GettingDMXValues)
p2 = Process(target=printtest2)
if __name__ == '__main__':
p1.start()
time.sleep(1)
p2.start()
For the first function, everything works fine, but when the second function tries to print the DMXValues
it says they are not defined, even though they have been printed in the other function.
I also can't access the Variable from anywhere else than the callback function
When debugging, depending on where the breakpoint is set, the Variable is either undefined or the Values I am expecting.
If I set the Variable at the start the second function prints the at the start defined Value, while the second one prints the Values I am expecting.
I searched but I did not find anyone with the same problem.
Aaron's comment about processes not being able to share global variables is your initial problem, but not you only problem. You have:
def printtest2():
while True:
print(DMXValues)
But even assuming you could share variables, (1) DMXValues
will not be defined until function callback
assigns a value to this variable and you will most likely get an exception if waiting 1 second to start the printtest2
process is enough time. And even assuming callback
creates the variable before printtest2
runs and you get no exception, you will be in an endless loop printing potentially the same value over and over again until a new value is assigned in callback
.
Assuming you want to print the value of DMXValues
once each time a new value is assigned, then you should be using a multiprocessing.Queue
to which one process will be putting new values and the other process will be getting them for printing:
from multiprocessing import Process, Queue
import time
import sacn
def GettingDMXValues(queue):
while True:
receiver = sacn.sACNreceiver(bind_address = "***.**.**.**")
receiver.start()
@receiver.listen_on('universe', universe=1)
def callback(packet):
#print(packet.dmxData)
global DMXValues
DMXValues = packet.dmxData
queue.put(DMXvalues)
receiver.join_multicast(1)
time.sleep(10)
receiver.leave_multicast(1)
receiver.stop()
def printtest2(queue):
while True:
DNXValues = queue.get()
print(DMXValues)
if __name__ == '__main__':
queue = Queue
p1 = Process(target=GettingDMXValues, args=(queue,))
p2 = Process(target=printtest2, args=(queue,))
p1.start()
#time.sleep(1) # Not necessary
p2.start()