简体   繁体   English

Python多处理输出

[英]Python multiprocessing output

I have a progress bar function. 我有进度条功能。 I would like to run this progress bar while the other function is doing processing. 我想在其他功能正在处理时运行此进度栏。 I have written a simple test code using multiprocessing module and it was not working well. 我已经使用多处理模块编写了一个简单的测试代码,但效果不佳。 My code: 我的代码:

from multiprocessing import Process
import time

def foo(thread):
    print time.ctime()
    time.sleep(10)
    print time.ctime()

def progress_bar(timer = 10):
    digits = 4
    delete = '\b' * 6
    time_slot = float(timer) / 100
    for i in range(1, 101):
        delete_bar = '\b' * 52
        if i == 1:
            bar = '|' + ' ' * 50 + '|'
        else:
            bar = '|' + '=' * (i / 2 - 1) + '>' + ' ' * (50 - i / 2) + '|'
        print "{0}{1:{2}}{3}{4}".format(delete, str(i) + '%', digits, bar, delete_bar),
        time.sleep(time_slot)
    print ''

def main():
    p1 = Process(target = foo1('this'))
    p1.start()
    p2 = Process(target = progress_bar())
    p2.start()
    p1.join()
    p2.join()

if __name__ == "__main__":
    main()

I was hoping that foo will print the current time first. 我希望foo首先打印当前时间。 Then progress_bar comes in to countdown for 10 seconds. 然后progress_bar进入倒数10秒钟。 Finally foo will output another time at the end. 最终foo将在末尾输出另一个时间。

Tue Apr  5 11:49:47 2016
100% =================================================>|
Tue Apr  5 11:49:57 2016

However what I got from the output is something like this: 但是我从输出中得到的是这样的:

Tue Apr  5 11:49:47 2016
Tue Apr  5 11:49:57 2016
100% =================================================>|

Is there a way to fix this in Python? 有没有办法在Python中解决此问题? Thank you very much! 非常感谢你!

This is happening because the function parameters are evaluated first, and when defining your p1 and p2 you're actually calling foo1('this') which executes the function at the definition of p1 , and progress_bar() at the instantiation of p2 . 之所以发生这种情况,是因为首先评估了函数参数,并且在定义p1p2 ,实际上是在调用foo1('this') ,它在p1的定义处执行函数,并在p2的实例化处执行progress_bar()

For a simple example that demonstrates this, see below: 有关演示此内容的简单示例,请参见下文:

def fn():
    print 'called'
    return 1

target1 = fn()
target = fn

print target1
print target

This prints: 打印:

>>> called # Got called as soon as you called fn via fn()
>>> 1 # Assigned the return value of fn to target1
>>> <function fn at 0x12DA77F0> # Didn't get called, assigned the fn definition to target

I got your example working with Thread s below ( Edit : After looking into some Process examples , it seems that they should work with the same syntax as the below code (just change the import and use Process instead of Thread ), but for some reason I just can't get the Process approach to print, even after copying the example. Might be due to my custom python setup, but not entirely sure.): 我在下面得到了使用Thread的示例( 编辑 :在研究了一些Process 示例之后 ,似乎它们应使用与以下代码相同的语法(只需更改导入并使用Process而不是Thread ),但是由于某些原因即使复制示例后,我也无法打印出Process方法。这可能是由于我自定义的python设置,但不是完全确定。):

from threading import Thread
import time

def foo(thread):
    print(time.ctime())
    time.sleep(10)
    print(time.ctime())

def progress_bar(timer = 10):
    digits = 4
    delete = '\b' * 6
    time_slot = float(timer) / 100
    for i in range(1, 101):
        delete_bar = '\b' * 52
        if i == 1:
            bar = '|' + ' ' * 50 + '|'
        else:
            bar = '|' + '=' * (i / 2 - 1) + '>' + ' ' * (50 - i / 2) + '|'
        print("{0}{1:{2}}{3}{4}".format(delete, str(i) + '%', digits, bar, delete_bar),)
        time.sleep(time_slot)
    print('')

def main():
    t1 = Thread(target=foo, args=('this',)) # Notice, not foo('this') <- this executes foo('this') at definition
    t1.start()
    t2 = Thread(target=progress_bar) # Again, notice, no parens - target is just the function definition
    t2.start()
    t1.join()
    t2.join()

This prints 此打印

Tue Apr 05 15:09:34 2016
('1%  |                                                  |',)
('2%  |>                                                 |',)
('3%  |>                                                 |',)
('4%  |=>                                                |',)
('5%  |=>                                                |',)
('6%  |==>                                               |',)
('7%  |==>                                               |',)
('8%  |===>                                              |',)
('9%  |===>                                              |',)
('10% |====>                                             |',)
('11% |====>                                             |',)
('12% |=====>                                            |',)
('13% |=====>                                            |',)
('14% |======>                                           |',)
('15% |======>                                           |',)
('16% |=======>                                          |',)
('17% |=======>                                          |',)
('18% |========>                                         |',)
('19% |========>                                         |',)
('20% |=========>                                        |',)
('21% |=========>                                        |',)
('22% |==========>                                       |',)
('23% |==========>                                       |',)
('24% |===========>                                      |',)
('25% |===========>                                      |',)
('26% |============>                                     |',)
('27% |============>                                     |',)
('28% |=============>                                    |',)
('29% |=============>                                    |',)
('30% |==============>                                   |',)
('31% |==============>                                   |',)
('32% |===============>                                  |',)
('33% |===============>                                  |',)
('34% |================>                                 |',)
('35% |================>                                 |',)
('36% |=================>                                |',)
('37% |=================>                                |',)
('38% |==================>                               |',)
('39% |==================>                               |',)
('40% |===================>                              |',)
('41% |===================>                              |',)
('42% |====================>                             |',)
('43% |====================>                             |',)
('44% |=====================>                            |',)
('45% |=====================>                            |',)
('46% |======================>                           |',)
('47% |======================>                           |',)
('48% |=======================>                          |',)
('49% |=======================>                          |',)
('50% |========================>                         |',)
('51% |========================>                         |',)
('52% |=========================>                        |',)
('53% |=========================>                        |',)
('54% |==========================>                       |',)
('55% |==========================>                       |',)
('56% |===========================>                      |',)
('57% |===========================>                      |',)
('58% |============================>                     |',)
('59% |============================>                     |',)
('60% |=============================>                    |',)
('61% |=============================>                    |',)
('62% |==============================>                   |',)
('63% |==============================>                   |',)
('64% |===============================>                  |',)
('65% |===============================>                  |',)
('66% |================================>                 |',)
('67% |================================>                 |',)
('68% |=================================>                |',)
('69% |=================================>                |',)
('70% |==================================>               |',)
('71% |==================================>               |',)
('72% |===================================>              |',)
('73% |===================================>              |',)
('74% |====================================>             |',)
('75% |====================================>             |',)
('76% |=====================================>            |',)
('77% |=====================================>            |',)
('78% |======================================>           |',)
('79% |======================================>           |',)
('80% |=======================================>          |',)
('81% |=======================================>          |',)
('82% |========================================>         |',)
('83% |========================================>         |',)
('84% |=========================================>        |',)
('85% |=========================================>        |',)
('86% |==========================================>       |',)
('87% |==========================================>       |',)
('88% |===========================================>      |',)
('89% |===========================================>      |',)
('90% |============================================>     |',)
('91% |============================================>     |',)
('92% |=============================================>    |',)
('93% |=============================================>    |',)
('94% |==============================================>   |',)
('95% |==============================================>   |',)
('96% |===============================================>  |',)
('97% |===============================================>  |',)
('98% |================================================> |',)
Tue Apr 05 15:09:44 2016
('99% |================================================> |',)
('100%|=================================================>|',)

Try this: 尝试这个:

from multiprocessing import Process
import time

def foo1(thread):
    print time.ctime()
    time.sleep(10.5)
    print time.ctime()

def progress_bar(timer = 10):
    digits = 4
    delete = '\b' * 6
    time_slot = float(timer) / 100
    for i in range(1, 101):
        delete_bar = '\b' * 52
        if i == 1:
            bar = '|' + ' ' * 50 + '|'
        else:
            bar = '|' + '=' * (i / 2 - 1) + '>' + ' ' * (50 - i / 2) + '|'
        print "{0}{1:{2}}{3}{4}".format(delete, str(i) + '%', digits, bar, delete_bar),
        time.sleep(time_slot)
    print ''

def main():
    p1 = Process(target=foo1, args=('this',))
    # p1 = Process(target = foo1('this'))
    p1.start()
    time.sleep(0.1)
    p2 = Process(target=progress_bar)
    p2.start()
    p1.join()
    p2.join()

if __name__ == "__main__":
    main()

Notice the different p1 Process. 注意不同的p1进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM