Python3多线程

时间:2017-02-06 11:35:57

标签: python-3.x python-multithreading

  

我正在制作一个Youtube下载程序脚本,遇到了多个>线程的困难。我把网址需要下载到一个队列中,并通过>一个新线程产生它们。下面是我的代码,错误在commant中。 >请指教。

from queue import Queue


#put all the urls in 'q'
q = Queue()
with open(r'c:\ProgramData\youtube_download\122.txt', 'r') as f : 
    for url in f.readlines():
        url = url.strip()
        q.put(url)  #totally 18 urls are stored in the queue


def My_download( url_d):

    yt = YouTube(url_d)
    video = yt.get('mp4', '720p')
    video.download(r'C:/Users/abc/Desktop')  # The default video directory

def main():

    while  not q.empty():
        url_d = q.get()
        q.task_done()
##    print(str(q.qsize()) + url_d)  >>until this step, everything works as expected

        t = Thread(target = My_download, args = url_d)  #>>TypeError: My_download() takes 1 positional argument but 92 were given
        t.start()

    q.join()


if __name__ == "__main__":

    main()

2 个答案:

答案 0 :(得分:1)

更改为

t = Thread(target = My_download, args = (url_d,))  

来自文档

  

args是目标调用的参数元组。默认为()。

当你发送一个字符串而不是元组时,它会将字符串解包为一个由n个元素组成的元组(在你的情况下是92,所以错误)

答案 1 :(得分:1)

Thread(target = My_download, args = url_d)

args是调用target的参数序列。调用My_download时会解压缩参数。例如,

Thread(target = My_download, args = [1, 2, 3])

最终会尝试拨打My_download(1, 2, 3)。这会触发TypeError,因为您的函数只需要一个参数。为了防止解包,您可以将args换成另一个长度为1的序列,例如

Thread(target = My_download, args = [url_d])

或修改My_download,使其使用*args语法接受任意数量的参数。