Python动态多线程变量不起作用

问题描述 投票:0回答:1

大家好!我只是Python的新手,并尝试编写第一个代码以在具有动态变量的5个线程中发布多部分数据,例如我有5个线程,在开始时我具有整数3000,在1个线程中我获得3000-1 = 2999,在下一个线程中我得到了2999-1 = 2998等,有人可以看看我的代码有什么问题吗?

  import requests
from multiprocessing import Pool
if __name__ == '__main__':
    p = Pool(1)
url = 'http://httpbin.org/post'
cookies = {'PHPSESSID': '2a55b01f46b3c7e5764b70666ac81cae'}
headers = {"user-agent":"undefined"}
data=(
        ('o_id', (None, '3732')),
        ('p_owner', (None, '3732')),
        ('p_name', (None, '1')),
        ('p_desc', (None, 'null')),
        ('save', (None, '')),
)
def make_request(id):
    requests.post(url, cookies=cookies, verify=False, headers=headers, files=data)
print(p.map(make_request, range(3000, 0, -1)))

NameError:未定义名称'p'

python post python-requests multiprocessing
1个回答
0
投票

从您的代码看来,p是在if __name__ == '__main__':中定义的

if __name__ == '__main__':
    p = Pool(1) // p is defined in this statement as it is intended. python depends on indents to map code.
url = 'http://httpbin.org/post'
cookies = {'PHPSESSID': '2a55b01f46b3c7e5764b70666ac81cae'}
headers = {"user-agent":"undefined"}
data=(
        ('o_id', (None, '3732')),
        ('p_owner', (None, '3732')),
        ('p_name', (None, '1')),
        ('p_desc', (None, 'null')),
        ('save', (None, '')),
)
def make_request(id):
    requests.post(url, cookies=cookies, verify=False, headers=headers, files=data)
print(p.map(make_request, range(3000, 0, -1)))

i 假定您想要做的是将所有内容都包含在该主语句中,在这种情况下,需要缩进代码的[[all。像这样:

if __name__ == '__main__': p = Pool(1) // in this example, all of the code is indented, which will allow it all to work. url = 'http://httpbin.org/post' cookies = {'PHPSESSID': '2a55b01f46b3c7e5764b70666ac81cae'} headers = {"user-agent":"undefined"} data=( ('o_id', (None, '3732')), ('p_owner', (None, '3732')), ('p_name', (None, '1')), ('p_desc', (None, 'null')), ('save', (None, '')), ) def make_request(id): requests.post(url, cookies=cookies, verify=False, headers=headers, files=data) print(p.map(make_request, range(3000, 0, -1)))
热门问题
推荐问题
最新问题