Python3 多线程

Python3 multi threading

I am working on a Youtube downloader script and met difficulty in multi->threading . I put the urls needs to be downloaded in a queue and get them one by >one with new thread spawning. Below is my code and the error are within the commant. >Please advise.

from queue import Queue


#put all the urls in 'q'
q = Queue()
with open(r'c:\ProgramData\youtube_download2.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()

改为

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

来自文档

args is the argument tuple for the target invocation. Defaults to ().

当您发送字符串而不是元组时,它将字符串解压缩为 n 个元素的元组(在您的情况下为 92,因此出现错误)

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 语法接受任意数量的参数。