Access a global variable to track status in multiprocessing
<p>I am writing a multiprocessing process that I want to monitor the status of.  How can I access my_var from thaht context?</p>

<pre><code>from multiprocessing import Process
import time

my_var = list()


def alter_my_var():
    global my_var
    for x in range(10):
        my_var.append(x)
        time.sleep(1)

p = Process(target=alter_my_var)
p.start()

while p.is_alive():
    print "Length of my_var is %i" % len(my_var)
    time.sleep(1)

p.join()

print "Done - final length of my_var is %s" % len(my_var)
</code></pre>

<p>Thanks</p>

<p>Use a <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.sharedctypes.multiprocessing.Manager" rel="nofollow"><em>Manager</em></a>, each process gets a copy of the list so you are not sharing one object, with <em>Manager().list()</em> you are:</p>

<pre><code>from multiprocessing import Process, Manager
import time

my_var = Manager().list()

def alter_my_var(my_var):
    for x in range(10):
        my_var.append(x)
        time.sleep(1)

p = Process(target=alter_my_var, args=(my_var, ))
p.start()
while p.is_alive():
    print "Length of my_var is %i" % len(my_var)
    time.sleep(1)
p.join()
print "Done - final length of my_var is %s" % len(my_var)
</code></pre>

<p>If we paste the code into Ipython, you can see the output:</p>

<pre><code>## -- End pasted text --
Length of my_var is 0
Length of my_var is 1
Length of my_var is 3
Length of my_var is 4
Length of my_var is 5
Length of my_var is 6
Length of my_var is 7
Length of my_var is 8
Length of my_var is 9
Length of my_var is 10
Done - final length of my_var is 10
</code></pre>

python