3

I spawn a seperate process to handle my cloud services. I spawnb it like this:

CldProc = Process(target=CloudRun)
CldProc.start()

and am wondering if I can have a shared dictionary between that CloudProc and my current main process?

EDIT: Alternatively I am thinking to use pickle to dump my data into a file from the process and load it back, this requires me to use join() to wait for the process to complete and exit.

2nd EDIT So, I now have my dict declared like mac_dict={} and then I fill it in my subprocess and want to access it in my main process. Now I just tried this:

>>> dict = dict()
>>> dict['A'] = 1
>>> print dict
{'A': 1}

So how does Python know that dict() should be called from Managers? Is there any examples I can follow?

stdcerr
  • 13,725
  • 25
  • 71
  • 128

2 Answers2

6

Got it, to simplify, I did it like this:

from multiprocessing import Process, Manager

def myf(myd):
    myd[1] = "HELLO WORLD!"

def proc(d):
    myf(d)

m=Manager()
locdict=m.dict()
locdict[2] = "HI BUDDY!"

p = Process(target=proc, args=(locdict,))

p.start()
p.join()
print locdict
stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • Glad to assist ... I was just about to come up with an example but you seem to have gotten it. – D.Shawley Jun 21 '13 at 02:34
  • It's worth noting here, that you do not have to pass locdict to the target function proc. The function myf will change locdict successsfully if you just did locdict[1] = 'blah' from it's body. – Totem Dec 20 '15 at 00:31
2

Take a look at multiprocessing.Manager and the Manager.dict() method in particular. They may serve your needs.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113