运维辞典@欢迎访问小站,如有疑问,可通过右侧QQ或底部邮箱联系,非常感谢@

python多线程跳过的坑

Python Administrator 866℃

执行下面的代码后,会报错如下内容,从提示来看,是参数出现了问题
Exception in thread Thread-1:
Traceback (most recent call last):
File “x:\Python34\lib\threading.py”, line 911, in _bootstrap_inner
self.run()
File “x:\Python34\lib\threading.py”, line 859, in run
self._target(*self._args, **self._kwargs)
TypeError: getURL() takes 1 positional argument but 22 were given

import requests
import threading

def getURL(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'}
    res = requests.get(url, headers=headers)
    return res     

threads = []
bingfa = range(1)

url="https://www.baidu.com/"

for i in bingfa:
    t = threading.Thread(target=getURL, args=(url))
    threads.append(t)

if __name__ == '__main__':
    for t in bingfa:
        threads[t].start()
    for t in bingfa:
        threads[t].join()

解决方法:
首先我们要明白,threading.Thread需要两个参数.
第一个(target)参数是线程函数变量,第二个参数(args)是一个数组变量参数,如果只传递一个值,就只需要i, 如果需要传递多个参数,那么还可以继续传递下去其他的参数,其中的逗号不能少,少了就不是数组了,就会出错。
于是,代码修改为如下内容

import requests
import threading

def getURL(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'}
    res = requests.get(url, headers=headers)
    return res     

threads = []
bingfa = range(1)

url="https://www.baidu.com/"

for i in bingfa:
    t = threading.Thread(target=getURL, args=(url,))
    threads.append(t)

if __name__ == '__main__':
    for t in bingfa:
        threads[t].start()
    for t in bingfa:
        threads[t].join()

码字很辛苦,转载请注明来自:《运维辞典 » python多线程跳过的坑

喜欢 (2)