Python:Catclear.py

From Botwiki

Jump to: navigation, search
import threading, Queue, time, traceback, re
import wikipedia, catlib, pagegenerators
 
PageQueue = None
Site = wikipedia.getSite()
 
# Defining the class Deletion
class DeletionThread(threading.Thread):
    def __init__(self, deletion_reason, page_callback):
        # Taking the mother class, thread, to use
        # multitasking
        threading.Thread.__init__(self)
        self.deletion_reason = deletion_reason
        self.page_callback = page_callback
        self.IsRunning = False
 
    def run(self):
        self.IsRunning = True
        global PageQueue
 
        wikipedia.output(u"Thread starting...")
 
        while self.IsRunning:
            try:
                Page = PageQueue.get(block = False)
 
                # Checking that the page is really an image and not something else.
                if not Page.isImage():
                    continue
 
                wikipedia.output(u'Now considering %s for deletion...' % Page)
 
                if self.page_callback(Page):
                    Page.delete(reason = self.deletion_reason, prompt = False)
 
                    TalkPage = Page.toggleTalkPage()
                    if TalkPage.exists():
                        wikipedia.output(u'Talk page of image exists.')
                        TalkPage.delete(reason=u'Talk page of a deleted page. ([[WP:CSD#G8]])', prompt=False)
 
            except (Queue.Empty, wikipedia.UserBlocked):
                self.IsRunning = False
 
            except:
                traceback.print_exc()
 
        wikipedia.output(u"Thread ends execution.")
 
def main(category, deletion_reason, page_callback, num_threads=1):
    global PageQueue
    PageQueue = Queue.Queue()
 
    for Page in pagegenerators.CategorizedPageGenerator(catlib.Category(Site, category)):
        PageQueue.put(Page)
 
    Threads = []
 
    wikipedia.output(u"Starting up %d threads..." % num_threads)
    for i in range(num_threads):
        NewThread = DeletionThread(deletion_reason, page_callback)
        NewThread.start()
        Threads.append(NewThread)
        time.sleep(3)
 
    ret = True
 
    while True:
        try:
            time.sleep(1)
            if len([t for t in Threads if t.IsRunning]) == 0:
                break
 
        except KeyboardInterrupt:
            ret = False
            wikipedia.output(u"Stopping threads...")
            for t in Threads:
                t.IsRunning = False
            break
 
    for t in Threads:
        t.IsRunning = False
        t.join()
 
    return ret
Personal tools