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



大家好!我只是 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)))

名称错误: 未定义名称"p">

从您的代码来看,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)))

假设您要做的是将所有内容都放在该主语句中,在这种情况下,所有代码都需要缩进。 像这样:

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)))

相关内容

  • 没有找到相关文章