Python3用gevent寫個檔案字串尋找器

來源:互聯網
上載者:User

標籤:def   部落格   數字   blank   一個   imp   odi   tor   http   

[本文出自天外歸雲的部落格園]

1、遞迴遍曆目錄下所有檔案並通過finder函數定位指定格式字串

2、用來尋找字串的finder函數是自己定義的,這裡定義了一個ip_port_finder通過Regex尋找ip:port格式(粗匹配:數字.數字.數字.數字:數字)的字串

3、用gevent來實現協程並發完成耗時任務

代碼如下:

# -*- coding: utf-8 -*-import refrom os.path import joinfrom os import walkfrom gevent import monkeyimport geventmonkey.patch_all()def ip_port_finder(str: str) -> bool:    pattern = re.compile(r".+\d+\.\d+\.\d+\.\d+:\d+")    matchObj = pattern.match(str)    if matchObj:        print("------")        print(f"發現目標:{matchObj.group(0)}")        return True    else:        return Falsedef find_in_file(file_path, finder):    with open(file_path, "r", encoding="utf-8", errors=‘ignore‘) as f:        for (num, value) in enumerate(f):            if finder(value):                print(f"檔案路徑:{file_path}")                print(f"所在行數:{num}")find_in_path_recursively = lambda path, finder: gevent.joinall(    [gevent.spawn(find_in_file, join(root, file_name), finder) for root, directories, f_names in walk(path) for     file_name in f_names])if __name__ == ‘__main__‘:    path = "E:\dev_codes\xxx"    find_in_path_recursively(path, ip_port_finder)

 

參考文章:

Python多任務實現之協程並發下載多圖片

Python3用gevent寫個檔案字串尋找器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.