Python 多处理:进程对象不可调用

Joh*_*aki 3 python multiprocessing python-multiprocessing

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

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()
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

alf*_*sin 5

向 a 运行的函数传递参数的方式Process不同 - 查看它显示的文档

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()
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

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()
Run Code Online (Sandbox Code Playgroud)

补充:
Luke 很好地抓住了(在下面的评论中)-您在执行以下操作时a使用变量名称覆盖函数a

a = Process(target=a, args=(3,))
Run Code Online (Sandbox Code Playgroud)

您应该使用不同的名称。

  • 打败我;快速说明一下,`def a(x)` 和 `a = Process...` 之间存在命名冲突。重命名变量或函数解决了这个问题,我让它在本地运行。@DJanssens args 元组中的尾随逗号很重要,没有它就无法运行。 (3认同)