JSimonsen
JSimonsen

Reputation: 2692

Python multiprocess output same line

I have a simple script here:

from multiprocessing import Process

def one():
    x = 1
    while x < 100:
        x +=1
        print(x)


def two():
    y = 100
    while y < 200:
        y += 1
        print(y)


if __name__=='__main__':
     p1 = Process(target = one)
     p1.start()
     p2 = Process(target = two)
     p2.start()

It works correctly and prints out a list of numbers fine.

I've been searching but so far have been unable to find any answer here. I'm wondering if its possible to print results in such def one and two return on the same line so I can compare the output. Something like:

1, 100
2, 101
3, 102
4, 103
...
...
100, 200

Maybe I'm missing something obvious or its not even possible.

Upvotes: 1

Views: 795

Answers (2)

accdias
accdias

Reputation: 5372

Maybe something like this but using generators:

def one():
    x = 1
    while x < 100:
        yield x
        x +=1


def two():
    y = 100
    while y < 200:
        yield y
        y += 1


if __name__=='__main__':
     p1 = one()
     p2 = two()

     for x, y in zip(p1, p2):
         print x, y

Upvotes: 1

viraptor
viraptor

Reputation: 34205

Doing it in the processes themselves would be pretty tricky. What you could do is have a separate process which has only the goal of receiving and printing data. Then you can have one pipe per output producer and only print something when you can collect a result from both processes.

Pseudocode:

def collector(p1, p2):
    for p1_out, p2_out in wait_for(p1, p2):
        print(p1_out, p2_out)

def one(out_pipe):
   for x in range(1, 100):
       out_pipe.send(x)

def two....

p1_writer, p1_reader = Pipe()
p2_writer, p2_reader = Pipe()
spawn(one, p1_writer)
spawn(two, p2_writer)
spawn(collector, (p1_reader, p2_reader))

Upvotes: 1

Related Questions