如何线程化应用程序?

时间:2015-06-25 14:46:21

标签: python python-multithreading

我将在这个问题中提到python。 好吧,假设我有一个重命名1000个文件的脚本。我如何多线程呢? 我考虑过将文件分成块,但它会使代码过于复杂,并且运行1000个线程,每个文件一个,不会起作用。

这是代码。

import os
import tkinter.messagebox
import tkinter.ttk
import tkinter.filedialog
from   tkinter import Tk, StringVar, Text, END

print("""
    A little reminder!
    Any file that gets renamed can't be undo,so don't screw around with this.
    NOTE : Careful with the extension,you might lose some files this way.
    """)

class Rename:

    def __init__(self,path): self.p = path

    def rename(self):
        try:

            files = os.listdir(self.p)
            i = 0
            os.chdir(self.p)
            while i <= len(files):
                ext = files[i].split(".")[-1]
                #You can change the renaming variable,for example you may add "file{}.{}".format(i,ext)..
                #also,don't play with the ext if you don't know what you're doing.. 
                os.rename(files[i],"{}.{}".format(i,ext))
                i += 1
                yield "Now renaming {}".format(files[i])

        except OSError as e: print("Error -> {}".format(e))
        except IndexError: pass

class GUI:

    def __init__(self):
        self.root = Tk()
        self.root.wm_title("FileRenamer")
        self.root.config(background = "black")

        # Label
        self.label = tkinter.ttk.Label(self.root, text = "Path: ")
        self.label.config(foreground = "white", background = "black", font = ("Arial", 16))
        self.label.grid(row = 0, column = 0)

        # File dialog
        self.path = StringVar()
        self.filepath = tkinter.ttk.Button(self.root, text = "Choose", command = self.askPath).grid(row = 0, column = 1)

        # TextWidget
        self.text = Text(self.root, height = 5, width = 50)
        self.text.config(foreground = "white", background = "black", font = ("Arial", 12))
        self.text.grid(row = 3, column = 0, columnspan = 2)

        # Button
        self.button = tkinter.ttk.Button(self.root, text = "Rename", command = self.rename)
        self.button.grid(row = 2, column = 1, columnspan = 2)

        self.root.mainloop()

    def askPath(self):
        self.path = tkinter.filedialog.askdirectory()

    def rename(self):
        path = os.path.abspath(self.path)
        rem  = Rename(path)
        for im in rem.rename():
            self.text.insert(END, "{}\n".format(im))

# Make sure that you add another "\" to the path you enter, otherwise you'll get an error.
r = GUI()

0 个答案:

没有答案