【问题标题】:Python multiprocessing: Process object not callablePython多处理:进程对象不可调用
【发布时间】:2015-07-06 21:56:43
【问题描述】:

所以,最近,我一直在试验多处理模块。我写了这个脚本来测试它:

from multiprocessing import Process
from time import sleep

def a(x):
    sleep(x)
    print ("goo")

a = Process(target=a(3))
b = Process(target=a(5))
c = Process(target=a(8))
d = Process(target=a(10))

if __name__ == "__main__":
    a.start()
    b.start()
    c.start()
    d.start()

但是,当我尝试运行它时,它会抛出此错误:

goo
Traceback (most recent call last):
  File "C:\Users\Andrew Wong\Desktop\Python\test.py", line 9, in <module>
    b = Process(target=a(5))
TypeError: 'Process' object is not callable

...我不知道发生了什么。 有谁知道发生了什么,我该如何解决?

【问题讨论】:

    标签: python multiprocessing python-multiprocessing


    【解决方案1】:

    将参数传递给由 Process 运行的函数的方式不同 - 查看 documentation 它显示:

    from multiprocessing import Process
    
    def f(name):
        print 'hello', name
    
    if __name__ == '__main__':
        p = Process(target=f, args=('bob',)) # that's how you should pass arguments
        p.start()
        p.join()
    

    或者在你的情况下:

    from multiprocessing import Process
    from time import sleep
    
    def a(x):
        sleep(x)
        print ("goo")
    
    e = Process(target=a, args=(3,))
    b = Process(target=a, args=(5,))
    c = Process(target=a, args=(8,))
    d = Process(target=a, args=(10,))
    
    if __name__ == "__main__":
        e.start()
        b.start()
        c.start()
        d.start()
    

    补充:
    Luke 的好消息(在下面的 cmets 中) - 您在执行此操作时使用变量名称 a 覆盖函数 a

    a = Process(target=a, args=(3,))
    

    您应该使用不同的名称。

    【讨论】:

    • 这并不能解决问题。它使第一个进程运行但无法运行其他进程,最终出现相同的错误:TypeError: 'Process' object is not callable。我也在调查是什么导致了这个问题,因为文档是这样说的。
    • 打败我;关于这一点的快速说明,def a(x)a = Process... 之间存在命名冲突。重命名变量或函数可以解决这个问题,我让它在本地运行。 @DJanssens args 元组中的尾随逗号很重要,没有它就无法运行。
    • 卢克!谢谢!我修复了命名错误,现在它可以工作了!
    • 修复命名冲突解决了 Luke Merret 的问题!不错的一个;)我建议有人将此作为真实答案发布,或者@alfasin 更新他的。
    猜你喜欢
    • 2023-01-31
    • 2018-01-01
    • 1970-01-01
    • 2020-05-18
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多