python實現文件搜索工具(簡易版)


在python學習過程中有一次需要進行GUI 的繪制,

而在python中有自帶的庫tkinter可以用來簡單的GUI編寫,於是轉而學習tkinter庫的使用。

學以致用,現在試着編寫一個簡單的磁文件搜索工具,

方法就是將指定的文件夾進行掃描遍歷,把其中的每個文件路徑數據存入數據庫,

然后使用數據庫搜索文件就很快捷。實現的效果大致如下:

 

 

整個程序分為大致幾個模塊:

主界面的繪制,

指定文件夾功能函數,

搜索文件功能函數,

ui線程與掃描線程同步函數,

掃描線程工作函數

 

要實現掃描文件功能時,

導入了一個這樣的模塊 disk.py 

這個模塊實現的功能就是將指定文件夾下的所有文件遍歷,並將路徑和所在盤符存到一個列表中返回

import os
import os.path as pt


def scan_file(path):
    result = []
    for root, dirs, files in os.walk(path):
        for f in files:
            file_path = pt.abspath(pt.join(root, f))

            result.append((file_path, file_path[0]))  # 保存路徑與盤符

    return result

然后我們需要將掃描到的文件存入到數據庫中,

因此需要編寫數據庫模塊 datebase.py

import sqlite3


class DataMgr:

    def __init__(self):
        # 創建或打開一個數據庫
        # check_same_thread 屬性用來規避多線程操作數據庫的問題
        self.conn = sqlite3.connect("file.db", check_same_thread=False)
        # 建表
        self.conn.execute('create table if not exists disk_table(' 
                          'id integer primary key autoincrement,' 
                          'file_path text,' 
                          'drive_letter text)')
        # 創建索引 用來提高搜索速度
        self.conn.execute('create index if not exists index_path on disk_table(file_path)')

    # 批量插入數據
    def batch_insert(self, data):
        for line in data:
            self.conn.execute('insert into disk_table values (null,?,?)', line)
        self.conn.commit()

    # 模糊搜索
    def query(self, key):
        cursor = self.conn.cursor()
        cursor.execute("select file_path from disk_table where file_path like ?", ('%{0}%'.format(key),))
        r = [row[0] for row in cursor]
        cursor.close()
        return r

    def close(self):
        self.conn.close()

 

還需要一個額外的模塊為 progressbar.py

這個模塊的功能是在掃描時彈出一個進度條窗口,

使得GUI功能看起來更完善

from tkinter import *
from tkinter import ttk


class GressBar:

    def start(self):
        top = Toplevel()  # 彈出式窗口,實現多窗口時經常用到
        self.master = top
        top.overrideredirect(True)  # 去除窗體的邊框
        top.title("進度條")
        Label(top, text="正在掃描選定路徑的文件,請稍等……", fg="blue").pack(pady=2)
        prog = ttk.Progressbar(top, mode='indeterminate', length=200)  # 創建進度條
        prog.pack(pady=10, padx=35)
        prog.start()

        top.resizable(False, False)  # 參數為false表示不允許改變窗口尺寸
        top.update()
        # 計算窗口大小,使顯示在屏幕中央
        curWidth = top.winfo_width()
        curHeight = top.winfo_height()
        scnWidth, scnHeight = top.maxsize()
        tmpcnf = '+%d+%d' % ((scnWidth - curWidth) / 2, (scnHeight - curHeight) / 2)
        top.geometry(tmpcnf)
        top.mainloop()

    def quit(self):
        if self.master:
            self.master.destroy()

 

主體的search.py 代碼:

  1 from tkinter import *
  2 from tkinter import ttk
  3 import tkinter.filedialog as dir
  4 import queue
  5 import threading
  6 import progressbar
  7 import disk
  8 from database import DataMgr
  9 
 10 
 11 class SearchUI:
 12 
 13     def __init__(self):
 14         # 創建一個消息隊列
 15         self.notify_queue = queue.Queue()
 16         root = Tk()
 17         self.master = root
 18         self.create_menu(root)
 19         self.create_content(root)
 20         self.path = 'D:'
 21         root.title('the search tool')
 22         root.update()
 23         # 在屏幕中心顯示窗體
 24         curWidth = root.winfo_width()
 25         curHeight = root.winfo_height()
 26         scnWidth, scnHeight = root.maxsize()  # 得到屏幕的寬度和高度
 27         tmpcnf = '+%d+%d' % ((scnWidth - curWidth)/2, (scnHeight-curHeight)/2)
 28         root.geometry(tmpcnf)
 29 
 30         # 創建一個進度條對話框實例
 31         self.gress_bar = progressbar.GressBar()
 32 
 33         # 創建一個數據庫的實例
 34         self.data_mgr = DataMgr()
 35 
 36         # 在UI線程啟動消息隊列循環
 37         self.process_msg()
 38         root.mainloop()
 39 
 40     # ui線程與掃描線程同步
 41     def process_msg(self):
 42         # after方法,相當於一個定時器,
 43         # 第一個參數是時間的毫秒值,
 44         # 第二個參數指定執行一個函數
 45         self.master.after(400, self.process_msg)
 46         # 這樣我們就在主線程建立了一個消息隊列,
 47         # 每隔一段時間去消息隊列里看看,
 48         # 有沒有什么消息是需要主線程去做的,
 49         # 有一點需要特別注意,
 50         # 主線程消息隊列里也不要干耗時操作,
 51         # 該隊列僅僅用來更新UI。
 52         while not self.notify_queue.empty():
 53             try:
 54                 msg = self.notify_queue.get()
 55                 if msg[0] == 1:
 56                     self.gress_bar.quit()
 57 
 58             except queue.Empty:
 59                 pass
 60 
 61     # 掃描線程工作
 62     def execute_asyn(self):
 63         # 定義一個scan函數,放入線程中去執行耗時掃描
 64         def scan(_queue):
 65             if self.path:
 66                 paths = disk.scan_file(self.path)  # 位於disk.py
 67                 self.data_mgr.batch_insert(paths)  # 位於database.py
 68 
 69             _queue.put((1,))
 70         th = threading.Thread(target=scan, args=(self.notify_queue,))
 71         th.setDaemon(True)  # 設置為守護進程
 72         th.start()
 73 
 74         self.gress_bar.start()
 75 
 76     # 菜單繪制
 77     def create_menu(self, root):
 78         menu = Menu(root)  # 創建菜單
 79 
 80         # 二級菜單
 81         file_menu = Menu(menu, tearoff=0)
 82         file_menu.add_command(label='設置路徑', command=self.open_dir)
 83         file_menu.add_separator()
 84         file_menu.add_command(label='掃描', command=self.execute_asyn)
 85 
 86         about_menu = Menu(menu, tearoff=0)
 87         about_menu.add_command(label='version1.0')
 88 
 89         # 在菜單欄中添加菜單
 90         menu.add_cascade(label='文件', menu=file_menu)
 91         menu.add_cascade(label='關於', menu=about_menu)
 92         root['menu'] = menu
 93 
 94     # 主界面繪制
 95     def create_content(self, root):
 96         lf = ttk.LabelFrame(root, text='文件搜索')
 97         lf.pack(fill=X, padx=15, pady=8)
 98 
 99         top_frame = Frame(lf)
100         top_frame.pack(fill=X, expand=YES, side=TOP, padx=15, pady=8)
101 
102         self.search_key = StringVar()
103         ttk.Entry(top_frame, textvariable=self.search_key, width=50).pack(fill=X, expand=YES, side=LEFT)
104         ttk.Button(top_frame, text="搜索", command=self.search_file).pack(padx=15, fill=X, expand=YES)
105 
106         bottom_frame = Frame(lf)
107         bottom_frame.pack(fill=BOTH, expand=YES, side=TOP, padx=15, pady=8)
108 
109         band = Frame(bottom_frame)
110         band.pack(fill=BOTH, expand=YES, side=TOP)
111 
112         self.list_val = StringVar()
113         listbox = Listbox(band, listvariable=self.list_val, height=18)
114         listbox.pack(side=LEFT, fill=X, expand=YES)
115 
116         vertical_bar = ttk.Scrollbar(band, orient=VERTICAL, command=listbox.yview)
117         vertical_bar.pack(side=RIGHT, fill=Y)
118         listbox['yscrollcommand'] = vertical_bar.set
119 
120         horizontal_bar = ttk.Scrollbar(bottom_frame, orient=HORIZONTAL, command=listbox.xview)
121         horizontal_bar.pack(side=BOTTOM, fill=X)
122         listbox['xscrollcommand'] = horizontal_bar.set
123 
124         # 給list動態設置數據,set方法傳入一個元組
125         self.list_val.set(('等待搜索',))
126 
127     # 搜索文件
128     def search_file(self):
129         if self.search_key.get():
130             result_data = self.data_mgr.query(self.search_key.get())
131             if result_data:
132                  self.list_val.set(tuple(result_data))
133 
134     # 指定文件夾
135     def open_dir(self):
136         d = dir.Directory()
137         self.path = d.show(initialdir=self.path)
138 
139 
140 if __name__ == '__main__':
141     SearchUI()

 

問題總結:

1.UI線程負責界面的繪制與更新,如果在UI線程中進行耗時操作,會影響界面的流暢性,所以需要異步線程。 

 此時的問題在於UI的主線程與異步線程的通信問題,為什么一定要兩個線程通信?

因為在大多數GUI界面編程中,異步線程都是不能對當前界面進行操作更新的,否則會引起界面混亂。

可以簡單的理解成  如果異步線程也操作主界面,則兩個線程對相同資源進行操作,就會導致混亂。

接下來的問題是tkinter中沒有提供接口進行線程通信,因此我們通過消息隊列的方式來同步線程,用到的類為Queue。

項目中當在消息隊列中檢索到消息為元組(1, )時,說明子線程(掃描)已經結束了,告知主線程可以結束子線程了。

 

2.掃描文件夾時需要將所選文件夾中的所有文件遍歷一遍,發現python中提供了方法os.walk(path), 可以直接達到這一效果,所以說python在寫代碼時確實提供了方便。

 

3.該磁盤搜索工具用到的原理是將文件路徑存到數據庫中,再進行檢索。 選用的數據庫為sqlite,已經可以滿足該項目的要求。在主線程創建數據庫,子線程操作數據庫,有可能出現問題,因此設置check_same_thread = false 來拒絕多線程的訪問。

 

4.在進行GUI編程時,打算在掃描等待時添加一個進度條顯示窗口,也就需要多窗口,用到了toplevel,表現為一個彈出式窗口,在使用toplevel時,要注意首先需要一個根窗口。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM