Visualizzazione dei risultati da 1 a 6 su 6

Discussione: [Python]Ottimizzazione

  1. #1

    [Python]Ottimizzazione

    Sto scrivendomi un news reader.
    Ora sono arrivato a skarikare i body dei msg e gli heade+subject(poi li fondero assieme).
    Pero volevo sapere se il mio code si puo ottimizzare un pochino.
    Ecco il code:
    codice:
    import os
    import sys
    import socket
    import nntplib
    import string
    
    __author__ = "Kleidemos (francesca8810@ti.it)"
    __version__ = "$Revision: 0.2 $"
    __date__ = "$Date: 2004/05/6 14:00:00 $"
    __copyright__ = "Copyright (c) 2004 Luca Francesca"
    __license__ = "Python"
    
    kb = 8 * 1024 # a kb unit 
    
    #
    # This class elaborate the NewsServerGestion downloaded files
    #
    class ArticleGestion:
        nws = ''
        article = []
        def Close(self):
             nws.quit()
        # Load into a GROUP_article.txt file the body of the article specified
        # into GROUP.txx file
        # Because this requied many time you should use a modal dialog or any
        # other mode (threads for example) to not block the application GUI
        def ParseGroup(self, server, gname):
            self.nws = nntplib.NNTP(server)
            self.nws.group(gname)
            self.fin = file(gname+"/"+gname+".txt", "r")
            self.fout = file(gname+"/"+gname+"_article.txt", "w")
            while 1:
                self.line = self.fin.readline()
                if not self.line:
                    self.fin.close()
                    self.fout.close()
                    break
                self.str_tmp = string.split(self.line, "\t")
                self.id = self.str_tmp[0]
                for i in self.nws.body(self.id)[3]:
                    try:
                        self.fout.write(i+"\n")
                    except:
                        print 'Error in write for file',
                        gname+"/"+gname+"_article.txt", '\n'
                    #self.fout.write("\n")
                
            self.fin.close()
            self.fout.close()
        # Merge the sebject-header file to the body file and build a group tree
        # to show
        # Because this requied many time you should use a modal dialog or any
        # other mode (threads for example) to not block the application GUI
        # TODO : 100%
        def BuildGroupTree(self, group, farticle, fsubject):
            pass
    
    
    #
    # This class download message from group and save it into a files
    #
    class NewsServerGestion:
        #
        __i = ''
        #
        __news = ''
        __msg = []
        #
        __group_state = []
        __beg = ''
        __end = ''
        #
        __stats = ''
        #single article
        __single_article = []
        __response = ''
        __number = ''
        __list = ''
        #article range
        __articles_header = []
        articles_list = []
        #article id
        __article_id = []
        def __init__(self, host):
            # Open a server connection
            self.news = nntplib.NNTP(host)
            self.news.getwelcome()
        # Send a article    
        def SendArticle(self, file):
            f = open(file)
            s.post(f)  
        # Download article id & header
        # Because this requied many time you should use a modal dialog or any
        # other mode (threads for example) to not block the application GUI
        def DownloadArticle(self):
            self.fname = self.group_state[4]+"/"+self.group_state[4]+".txt"
            self.articles_list = self.news.xover('subject', self.beg + '-' + self.end, self.fname)
        # Save group info
        def PrintGroupInfo(self, gname):
            if not os.path.exists(gname):
                os.mkdir(gname)
            self.group_state = self.news.group(gname)
            self.stats = self.group_state[0] # set group info
            self.beg = self.group_state[2]   # start message
            self.end = self.group_state[3]   # end message
            f = open(gname+"/"+gname+"_stat.txt", "w")
            try:
                f.write(self.stats)
            except:
                print 'Error in write stat files for', gname, 'group\n'
            f.close()
        def Close(self):
            self.news.quit()
            
    
    if __name__ == "__main__":
       
        print "Test NewsServerGestione on ", sys.getwindowsversion()
    
        n = NewsServerGestion("news.tin.it")
        
        n.PrintGroupInfo("it.comp.lang.python")
         
        n.DownloadArticle()
        
        n.Close()
    
        msg = ArticleGestion()
        
        msg.ParseGroup("news.tin.it", "it.comp.lang.python")
        
        msg.Close()

    Tnk 1000000000000000000
    La stupidità umana e l'universo sono infinite.
    Della seconda non sono certo(Einstein)

    Gnu/Linux User

  2. #2
    invece di usare dei thread o altro puoi usare le socket non blocking DD

    le librerie dovrebberò avere una funzione che "esegue" gli eventi
    in questo modo ti fai una funzione che lancia il pool o il select sulla lista delle socket e poi sempre dentro questo ciclo lancia questa funzione per svolgere gli eventi ^^

  3. #3
    spiegati meglio
    Di socket nn so moltissimo.
    La stupidità umana e l'universo sono infinite.
    Della seconda non sono certo(Einstein)

    Gnu/Linux User

  4. #4
    le socket asincrone non mettono in pausa il programma in attesa di ricevere i dati
    semplicemente se non c'è ne sono disponibili non ti ritornano nulla (se cosi si può dire)

    praticamente si usa il select (il pool nn lo so usare) a cui si passano un X di parametri...3 array (o mappe) di sockets, il primo parametro sono le socket dalle quali si attende un evento di arrivo dei dati, il secondo parametri serve per vedere se le socket nella lista hanno il buffer per la scrittura pieno, mentre il terzo parametro serve a vedere se le socket hanno dato errore, ma non serve quasi mai xche il primo, quando salta una connessione, e vai per leggere il contenuto (chiudendo la connessione la socket ha un'evento per la lettura) ti ritorna un FALSE ^^

    facendo cosi puoi gestire tutto in maniera asincrona

  5. #5
    dal manuale python 2.3.3:

    setblocking(flag)

    Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn't find any data, or if a send() call can't immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0); s.setblocking(1) is equivalent to s.settimeout(None).
    La stupidità umana e l'universo sono infinite.
    Della seconda non sono certo(Einstein)

    Gnu/Linux User

  6. #6
    cmq ho notato che tu usi il modulo nntp, dovresti vedere di prendere i sorgenti del modulo e modificarli per trasformarli usando le socket non blocking ^^

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.