开发者社区> 问答> 正文

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

name错误:没有定义名称“p” 问题来源StackOverflow 地址:/questions/59380415/python-dynamical-multithread-variable-not-working

展开
收起
kun坤 2019-12-28 14:18:39 516 0
1 条回答
写回答
取消 提交回答
  • 从你的代码中,看起来p是在if中定义的:

    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)))
    
    2019-12-28 14:18:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载