Python Thread code sample

教程:【【2021最新版】Python 并发编程实战,用多线程、多进程、多协程加速程序运行】 https://www.bilibili.com/video/BV1bK411A7tV/?share_source=copy_web&vd_source=3c8dced09a6723bcd0d0926c6ac558f9

Thread\blog_spider.py

import requests
from bs4 import BeautifulSoup

urls = [
        f"https://www.cnblogs.com/#p{page}"
       for page in range(1, 50+1)
    ]


def craw(url):
    r = requests.get(url)
    return r.text


def parse(html):
    soup = BeautifulSoup(html, 'html.parser')
    links = soup.find_all('a', class_='post-item-title')
    return [(link['href'], link.get_text()) for link in links]


# craw(urls[0])
if __name__ == '__main__':
    for result in parse(craw(urls[2])):
        print(result)

1. threading

multi_thread_craw.py

import Thread.blog_spider as blog_spider
import threading
import time


def single_thread():
    for url in blog_spider.urls:
        blog_spider.craw(url)


def multi_thread():
    threads = []
    for url in blog_spider.urls:
        threads.append(
            threading.Thread(target=blog_spider.craw, args=(url,))
        )
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    start = time.time()
    single_thread()
    end = time.time()
    print('single thread cost:', end - start, 'sec')

    start = time.time()
    multi_thread()
    end = time.time()
    print('single thread cost:', end - start, 'sec')

2. queue.Queue()

producer_consumer_spider.py

import queue
import Thread.blog_spider as blog_spider
import threading
import time
import random


def do_craw(url_queue: queue.Queue, html_queue: queue.Queue):
    while True:
        url = url_queue.get()
        html = blog_spider.craw(url)
        html_queue.put(html)
        print(threading.current_thread().name, f" craw {url}",
              "url_queue.size=", url_queue.qsize())
        time.sleep(random.randint(1, 2))


def do_pare(html_queue: queue.Queue, fout):
    while True:
        html = html_queue.get()
        results = blog_spider.parse(html)
        for result in results:
            fout.write(str(result) + '\n')
        print(threading.current_thread().name, " results.size", len(results),
              "html_queue.size=", html_queue.qsize())
        time.sleep(random.randint(1, 2))


if __name__ == '__main__':
    url_queue = queue.Queue()
    html_queue = queue.Queue()
    for url in blog_spider.urls:
        url_queue.put(url)

    print(url_queue)
    for idx in range(3):
        t = threading.Thread(target=do_craw, args=(url_queue, html_queue), name=f"craw{idx}")
        t.start()

    fout = open("02.data.txt", "w")
    for idx in range(2):
        t = threading.Thread(target=do_pare, args=(html_queue, fout), name=f"parse{idx}")
        t.start()

3. lock

lock_concurrent.py

import threading
import time
lock = threading.Lock()


class Account:
    def __init__(self, blance):
        self.blcance = blance


def draw(account, amount):
    with lock:
        if account.blcance >= amount:
            time.sleep(0.1)
            print(threading.current_thread().name, "取钱成功")
            account.blcance -= amount
            print("余额", account.blcance)
        else:
            print(threading.current_thread().name, "取钱失败")
            print("余额", account.blcance)


if __name__ == '__main__':
    account = Account(1000)
    ta = threading.Thread(target=draw, args=(account, 800), name='ta')
    tb = threading.Thread(target=draw, args=(account, 800), name='tb')

    ta.start()
    tb.start()

4. asyncio

import asyncio
import aiohttp
import Thread.blog_spider as blog_spider
import time

async def async_craw(url):
    print("craw url:", url)
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            result = await resp.text()
            print(f"craw url:{url}, {len(result)}")

loop = asyncio.get_event_loop()

tasks = [
    loop.create_task(async_craw(url))
    for url in blog_spider.urls
]

start = time.time()
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print("time", end - start, 'sec')

5. semaphore

import asyncio
import aiohttp
import Thread.blog_spider as blog_spider
import time


semaphore = asyncio.Semaphore(10)


async def async_craw(url):
    async with semaphore:
        print("craw url:", url)
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                result = await resp.text()
                # await asyncio.sleep(5)
                print(f"craw url:{url}, {len(result)}")

loop = asyncio.get_event_loop()

tasks = [
    loop.create_task(async_craw(url))
    for url in blog_spider.urls
]

start = time.time()
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print("time", end - start, 'sec')

<think>嗯,用户提出了一个JMeter测试中响应代码500和Python程序执行时报错的问题。从错误信息来看,核心是CreateProcess error=267(目录名称无效),这通常指向路径处理问题。 用户可能正在做接口自动化测试,通过JMeter调用Python脚本处理数据时触发了这个异常。ta的引用里提到Jenkins工作目录"D:\Jenkins\...jmeter_test",这个带空格的路径很关键——Windows系统对带空格的路径处理需要特殊注意。 先拆解两个问题: 第一,JMeter返回500是服务端错误,但结合后续脚本执行错误,很可能是因为Python脚本未能正确执行导致测试数据缺失,进而引发服务端异常。需要确认脚本是否真的运行了。 第二,error=267是个明确的Windows系统错误码,查证MSDN文档确认是目录路径格式问题。可能的情况有: - 路径包含空格但未加引号(比如"D:\test dir"应该写成"\"D:\test dir\"") - 路径中存在非法字符(如|>*等) - 路径超过260字符限制(虽然错误码不同,但有时会伴随发生) 特别注意用户环境是Jenkins+JMeter,这类自动化工具经常需要拼接路径。检查点应该包括: 1. JMeter的OS Process Sampler中调用命令的路径写法 2. 是否通过环境变量传递路径(需要检查变量值两端的引号) 3. Jenkins工作空间路径是否包含特殊字符 突然想到用户引用[3]提到过mysql调用错误,虽然场景不同但错误模式相似,都是外部程序调用失败。这说明用户可能在多个场景遇到相同机制的问题,解决这个可能避免后续类似错误。 解决方案层面,除了基础路径规范,建议用户添加路径验证步骤: 在JMeter中添加JSR223采样器执行打印当前工作目录,或者让Python脚本先输出os.getcwd()确认实际运行时路径。这种诊断方式比盲目修改更高效。 用户似乎对技术细节比较熟悉(能精确指出错误码),回复时需要保持技术严谨性。但要注意避免堆砌术语,重点给出可操作步骤,比如具体演示如何用groovy脚本获取规范路径。 </think>JMeter测试出现HTTP 500错误同时触发Python执行异常`CreateProcess error=267`的根本原因在于**路径解析失败**,以下是系统级分析及解决方案: --- ### **问题根源分析** 1. **路径格式错误 (核心问题)** - `CreateProcess error=267`是Windows系统错误码,表示**目录名称无效或格式错误**(例如:路径包含非法字符、未转义空格、长度超限等) - Jenkins工作目录示例:`"D:\Jenkins\Jenkins_home\workspace\jmeter_test"`若包含空格或特殊字符,需**显式添加引号**包裹完整路径 2. **JMeter与Python交互故障链** ```mermaid graph TD A[JMeter发起请求] --> B{服务端响应500} A --> C[调用Python脚本] C --> D[路径解析失败 error=267] D --> E[脚本未执行] E --> B[业务逻辑缺失导致500] ``` 3. **HTTP 500的关联性** - Python脚本因路径错误未能生成预期测试数据 - 服务端依赖此数据时抛出未处理异常 - 本质是**前置脚本执行失败引发的连带故障** --- ### **解决方案** #### 1. **修复路径错误 (关键一步)** - **JMeter调用命令示例**: ```bash # 错误写法(未处理空格) python D:\test dir\script.py # 正确写法(引号包裹路径) python "D:\test dir\script.py" ``` - **Jenkins管道脚本修正**: ```groovy stage(&#39;Run Python&#39;) { steps { // 使用三重引号确保路径安全 bat """python "${WORKSPACE}\\jmeter_scripts\\data_processor.py" """ } } ``` #### 2. **验证环境变量** - 在JMeter中添加 **JSR223 Sampler** 打印路径: ```groovy log.info("当前工作目录: " + new File(".").getCanonicalPath()) System.getenv().each { k,v -> log.info("ENV: " + k + "=" + v) } ``` - 检查`Path`环境变量是否包含Python安装目录(如`C:\Python39`) #### 3. **HTTP 500独立排查** | 检查点 | 工具/方法 | |----------------|-----------------------------| | 服务端日志 | 查看Tomcat/Catalina日志 | | 请求参数完整性 | JMeter → **View Results Tree** | | 后端依赖服务 | 数据库连接/API连通性测试 | #### 4. **防御性编程增强** - Python脚本首行添加路径校验: ```python import os,sys if not os.path.exists(sys.argv[1]): sys.exit(f"错误:路径 {sys.argv[1]} 不存在") # 明确退出代码 ``` --- ### **预防措施** 1. **路径规范化工具** - 使用`os.path.normpath()`处理路径(Python) - JMeter变量引用改用`${__groovy(path.replace("\\", "\\\\"))}` 2. **Jenkins安全配置** ```bash # 全局路径长度检查(PowerShell) Get-ChildItem -Recurse | Where { $_.FullName.Length -gt 240 } | Select FullName ``` 3. **错误码映射表** | 错误码 | 含义 | 解决方案 | |-------|----------------------|----------------------| | 267 | 目录名称无效 | 引号包裹路径 | | 2 | 文件不存在 | 检查环境变量 | | 5 | 访问拒绝 | 权限配置 | > 路径问题在Windows环境下尤为常见,**路径长度超过260字符**也可能触发此错误(需启用[长路径支持注册表项](https://learn.microsoft.com/zh-cn/windows/win32/fileio/maximum-file-path-limitation)) --- **
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值