You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python多进程的子进程内根据条件切换函数迭代器?

解决方案

要实现子进程触发条件后主进程切换URL并重启词表遍历,核心是通过进程间通信让子进程把触发信号传递给主进程,由主进程控制迭代流程。原代码直接启动所有子进程,无法实时响应触发条件,以下是修改后的实现:

from multiprocessing import Process, Queue
import requests
import os


def worker(url, data, queue):
    try:
        response = requests.post(url, data=data, timeout=15)
        if "Match" in response.text:
            print(f'Match found for {url} with word: {data["word"]}')
            queue.put(("match", url))
        if "Wrong word" in response.text:
            print(f'Wrong word detected for {url}, switching URL...')
            queue.put(("wrong", url))
    except Exception as e:
        print(f'Error with {url}: {str(e)}')
        queue.put(("error", url))


def init():
    urls = open('urls.txt').read().splitlines()
    # 对词表文件排序,保证每次重启遍历的顺序一致
    word_files = sorted(os.listdir('wordlists'))
    
    for url_idx in range(len(urls)):
        current_url = urls[url_idx]
        queue = Queue()
        active_processes = []
        should_switch = False
        
        # 遍历词表文件
        for file in word_files:
            if should_switch:
                break
            words = open(f'wordlists/{file}').read().splitlines()
            
            # 遍历当前文件的单词
            for word in words:
                if should_switch:
                    break
                data = {'word': word}
                # 启动子进程并加入管理列表
                p = Process(target=worker, args=(current_url, data, queue))
                p.start()
                active_processes.append(p)
                
                # 非阻塞检查队列,及时响应触发信号
                while not queue.empty():
                    signal, signal_url = queue.get()
                    if signal == "wrong" and signal_url == current_url:
                        # 终止当前URL的所有子进程
                        for p in active_processes:
                            if p.is_alive():
                                p.terminate()
                                p.join()
                        should_switch = True
                        break
        
        # 如果触发切换,直接进入下一个URL
        if should_switch:
            continue


if __name__ == '__main__':
    init()

关键修改说明

  • 进程间通信:用Queue让子进程向主进程发送触发信号("wrong"/"match"/"error")。
  • 子进程管理:主进程维护当前URL的所有活跃子进程,收到切换信号后立即终止这些进程,避免无效任务继续运行。
  • 流程控制:通过should_switch标记控制循环中断,触发后直接切换到下一个URL,并重新从排序后的第一个词表文件开始遍历。
  • 遍历顺序稳定:对词表文件名排序,确保每次重启遍历的顺序一致,避免随机遍历。

内容的提问来源于stack exchange,提问作者loopthebestkarl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:00:52