【问题标题】:Python multiprocessing outputPython 多处理输出
【发布时间】:2016-04-05 18:52:41
【问题描述】:

我有一个进度条功能。我想在另一个函数进行处理时运行这个进度条。我使用多处理模块编写了一个简单的测试代码,但效果不佳。我的代码:

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()

我希望 foo 会首先打印当前时间。然后progress_bar 进入倒计时10 秒。最后 foo 会在最后输出另一个时间。

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

但是我从输出中得到的是这样的:

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

有没有办法在 Python 中解决这个问题? 非常感谢!

【问题讨论】:

    标签: python python-multiprocessing


    【解决方案1】:

    试试这个:

    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()
    

    注意不同的 p1 进程。

    【讨论】:

    • 这就是我想要的!非常感谢!
    【解决方案2】:

    发生这种情况是因为首先评估函数参数,并且在定义 p1p2 时,您实际上是在调用 foo1('this'),它在 p1progress_bar() 的定义处执行函数p2 的实例化。

    有关演示这一点的简单示例,请参见下文:

    def fn():
        print 'called'
        return 1
    
    target1 = fn()
    target = fn
    
    print target1
    print target
    

    打印出来:

    >>> 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
    

    我让您的示例与下面的 Threads 一起使用(编辑:在查看了一些 Process examples 之后,它们似乎应该使用与以下代码相同的语法(只需更改导入并使用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()
    

    打印出来

    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%|=================================================>|',)
    

    【讨论】:

    • 尝试重新运行Process 示例再次使我的计算机崩溃-.-
    • 看来问题出在 Process(target = foo(1)) 调用行。我可以使用 Process(target = foo, args = ('this',)) 输出正确的结果。非常感谢!
    • 实际上还不是全部。 您在实例化第二个进程时也需要去掉括号。 有了它们,您的代码就相当于只说p1.start() 然后progress_bar() 这只是在主进程上运行,使第二个进程毫无意义。您可以尝试添加第三个进程以了解我的意思。
    • @yc2986 查看答案中添加的另一个基本示例。
    猜你喜欢
    • 2019-01-16
    • 2021-05-13
    • 2013-03-30
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多