在线程错误中从函数返回值

时间:2018-09-20 14:16:31

标签: python multithreading

我编写了一个脚本,其中一个函数使用“多线程”一起调用2个不同的函数。

def video_image(link_ID):
    threadp = ThreadPool(processes=1)
    res = threadp.apply_async(displayImage,( link_ID))
    return_val = res.get()
    tid = Thread(target=publishIAmFree)
    tid.start()
    if return_val == True:
        ............
        ............

def displayImage(link_ID):
    playFlag = True
    os.system("pkill feh")
    cmd = "feh /home/fa/Desktop/%s" % (link_ID)
    os.system(cmd)
    return playFlag

但是,我收到此错误。

  File "C:/Users/user1/PycharmProjects/MediPlayerStructured/venv/Include/main_new_concept.py", line 281, in videoImageFunction
video_image(link_ID)
  File "C:/Users/user1/PycharmProjects/MediPlayerStructured/venv/Include/main_new_concept.py", line 349, in video_image
return_val = res.get()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python37\lib\multiprocessing\pool.py", line 657, in get
raise self._value
  File "C:\Users\user1\AppData\Local\Programs\Python\Python37\lib\multiprocessing\pool.py", line 121, in worker
result = (True, func(*args, **kwds))
TypeError: displayImage() takes 1 positional argument but 23 were given

这是什么错误

TypeError: displayImage() takes 1 positional argument but 23 were given

该如何解决?

1 个答案:

答案 0 :(得分:1)

您缺少逗号。重现此内容(在Python2中)的简单方法是

>>> apply(len, ('test'))
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: len() takes exactly one argument (4 given)

>>> apply(len, ('test',))
4

发生问题是因为args参数被视为参数序列。我假设您要传递一个字符串,该字符串是一个序列,因此每个字符都成为一个单独的参数。

调用res = threadp.apply_async(displayImage, (link_ID, ))将使Python按照您的意思进行解释,并将link_ID作为序列的第一个元素。