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

Python多线程优化:复用单一函数,避免为每个线程创建独立函数

优化批量网络扫描的多线程代码:消除重复函数,复用核心逻辑

Hey there! I noticed you originally implemented your batch network scan with four nearly identical functions (f1-f4) paired with separate threads—this creates unnecessary duplicate code and makes future tweaks way more tedious. Let's streamline this by reusing a single universal scan function, where each thread gets its own unique parameter to handle a distinct segment of the scan range.

优化后的完整代码

import webbrowser
import urllib.request
import re
import sys
import threading
from threading import Thread

print("请输入前两个字节:")
r = input(str(":"))
i = 0
x = 1

"""
--------------------------------------------------------
------------------------通用扫描函数------------------------
--------------------------------------------------------
"""
def scan_func(x, i, r, offset):
    while i < 64:
        i += 1
        y = str(x)
        u0 = str(i + offset)
        try:
            t0 = urllib.request.urlopen('http://'+r+'.'+y+'.'+u0, timeout=1).getcode()
        except:
            t0 = 'http://'+r+'.'+y+'.'+u0+' ---NOP---'
        print(t0)
        if t0 == 200:
            print('http://'+r+'.'+y+'.'+u0+' ---OUI---')
            url = 'http://'+r+'.'+y+'.'+u0
            req = urllib.request.Request(url)
            resp = urllib.request.urlopen(req)
            respData = resp.read()
            Title = re.findall(r'e&gt;(.*?)&lt;/title&gt;',str(respData))
            Title = str(Title)
            print(Title)
            print('http://'+r+'.'+y+'.'+u0+' ---'+Title+'---', file=open("outpute.txt", "a"))
        if i == 64:
            i = 0
            x += 1

"""
--------------------------------------------------------
------------------------启动线程------------------------
--------------------------------------------------------
"""
if __name__ == "__main__":
    offsets = [0, 64, 128, 192]
    threads = []
    for offset in offsets:
        tr = Thread(target=scan_func, args=[x, i, r, offset])
        tr.setDaemon(True)
        threads.append(tr)
        tr.start()

核心优化思路

  • 抽象通用扫描逻辑:把原来重复的f1-f4函数合并成一个scan_func,新增offset参数作为区分不同线程任务的关键
  • 参数化线程任务:每个线程启动时传入不同的offset值(0、64、128、192),这样四个线程会分别扫描[1-64]、[65-128]、[129-192]、[193-256]这四个IP段,完美覆盖原来四个函数的分工
  • 统一线程管理:用列表存储所有线程对象,方便后续扩展(比如增加更多线程)或者做线程同步操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:16:36