Im having trouble getting consistent logging from within a process in a process pool while using map
.
Here is the function being called in the process pool:
from multiprocessing import Pool, Lock
lock = Lock()
def ping(host):
name, address = host
with lock:
sys.stdout.write("\npinging " + name + " at address " + address)
sys.stdout.flush()
pop = Popen(['ping', '-n', '1', address], stdout=PIPE)
pop.communicate() # We use communicate to not block the stdin stream, since we are going to need the return code from it
res = pop.wait() # This gets us the return code we want
status = "OK"
if res != 0:
status = "FAILED"
with lock:
sys.stdout.write("\n" + name + " , " + address + " , " + status + "\n")
sys.stdout.flush()
return (name, address, status)
pool declaration:
pool = Pool(processes=4)
results = pool.map(ping, hosts)
print results
For some reason, im getting pretty inconsistent output from this. I assume it is because more than one process tries to print at a given moment, however, shouldnt Lock()
solve this?
Here are the types of outputs im getting:
this i'd consider good:
pinging CP_RESERVED_MS at address 12.13.14.15
pinging test at address 1.1.1.1
pinging test_diplicate at address 1.1.1.2
CP_RESERVED_MS , 12.13.14.15 , FAILED
test_diplicate , 1.1.1.2 , FAILED
test , 1.1.1.1 , FAILED
[(u'CP_RESERVED_MS', u'12.13.14.15', 'FAILED'), (u'test', u'1.1.1.1', 'FAILED'), (u'test_diplicate', u'1.1.1.2', 'FAILED')]
Then suddenly it gets jumbled:
pinging CP_RESERVED_MS at address 12.13.14.15pinging test at address 1.1.1.1
pinging test_diplicate at address 1.1.1.2
test_diplicate , 1.1.1.2 , FAILED
CP_RESERVED_MS , 12.13.14.15 , FAILED
test , 1.1.1.1 , FAILED
[(u'CP_RESERVED_MS', u'12.13.14.15', 'FAILED'), (u'test', u'1.1.1.1', 'FAILED'), (u'test_diplicate', u'1.1.1.2', 'FAILED')]
wont new-line, missing new-lines, etc
why is this?
p.s im using windows 10 64 bit