[Python] Print skipping newline

Discussão em 'Python' iniciado por Stack, Abril 4, 2025.

  1. Stack

    Stack Membro Participativo

    I've got a question based off an answer I saw. It uses a thread pool to manage threads but each thread prints 'Going to sleep... i', sleeps for i time and then prints 'Slept..'. my question is why it prints 'Going to sleep...Going to sleep...Going to sleep...'? It doesn't print them on a newline unless I explicitly add \n to the end of the string. Here is my output without the \n. `

    Going to sleep...Going to sleep...Going to sleep...


    Slept ..0
    Going to sleep...
    Slept ..1
    Going to sleep...
    Slept ..2
    Slept ..3
    Slept ..4
    done!!`


    Here is my output with the newline

    Going to sleep...
    Going to sleep...
    Going to sleep...



    Slept ..0
    Going to sleep...

    Slept ..1
    Going to sleep...

    Slept ..2
    Slept ..3
    Slept ..4
    done!!


    The spaces between Going to sleep... and the first Slept.. seem strange to me as well.

    Here's the code

    import time
    from multiprocessing.dummy import Pool

    def run(i):
    print "Going to sleep...\n"
    time.sleep(i)
    print ("Slept .." + str(i))

    p = Pool(3)

    res = [p.apply_async(run, (i,)) for i in range(5)]

    p.close()
    p.join()

    print "done!!"

    Continue reading...

Compartilhe esta Página