# # Simpy 0.1 - Libreria realizzata per semplici operazioni su files e variabili. # Uso: # Basta semplicemente importare il modulo simpy, controllando che esso # sia nella stessa cartella dello script nel quale volete utilizzare la libreria: # # Esempio: # >>> import simpy # # ----------------------------------------------- # # Copyright (C) 2006 Simone Economo # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ----------------------------------------------- # # Autore: Simone Economo (aka eKoeS) (http://www.lineheight.net) # Contatto: my.ekoes@gmail.com # # Potete trovare informazioni sulla licenza GPL2 in uso su: # http://www.gnu.org/licenses/gpl.html # ITA (Non ufficiale): http://www.softwarelibero.it/gnudoc/gpl.it.txt # class _var: # Operazioni sulle variabili def mreplace(self, varname, oldlist, newlist): """ Funziona come str_replace in php, permettendo di rimpiazzare piu' elementi, tramite l'uso delle liste python. Sintassi: simpy._var.mreplace(variabile, vecchi, nuovi) Ritorna: 0 -> Operazione non riuscita ("vecchi" e/o "nuovi" non sono liste) variabile -> Operazione riuscita Esempio (da console interattiva): >>> mytext = "Mi piacciono tanto gli spaghetti" >>> newtext = simpy._var.mreplace(mytext, ["Mi", "tanto", "gli spaghetti"], ["Ti", "poco", "i carciofi"]) >>> print newtext Ti piacciono poco i carciofi >>> """ if (type(oldlist) is list and type(newlist) is list) and (len(oldlist) == len(newlist)): for terms in range(len(oldlist)): varname = varname.replace(oldlist[terms], newlist[terms]) return varname else: return 0 class _file: # Operazioni sui files def check(self, filename): """ Funziona come file_exists in php, permettendo di controllare se un file esiste o no. Sintassi: simpy._file.check(filename) Ritorna: 0 -> Il file non esiste 1 -> Il file esiste Esempio (da console interattiva): >>> simpy._file.check("/usr/lib/mazinga.so") 0 >>> simpy._file.check("/usr/lib/libsvg-cairo.a") 1 >>> """ try: open(filename) return 1 except IOError: return 0 def fwrite(self, filename, text, mode = None): """ Scrive su file, permettendo di impostare alcune modalita' di scrittura. Sintassi: simpy._file.fwrite(filename, testo[, modalita']) Le modalita' sono: "append" - Scrive alla fine del file o dopo la riga specificata "append" - Scrive alla fine del file "append@n" - Scrive alla riga numero "n" del file "top" - Scrive all'inizio del file "replace" - Sostituisce una o piu' righe del file "replace@n" - Sostituisce la riga numero "n" del file "replace@n:n2" - Sostituisce le righe selezionate in base al concetto slice di python. Per maggiori informazioni visita: http://it.diveintopython.org/getting_to_know_python/lists.html NOTA: Se non viene specificato il mode, la funzione (ri)crea il file, generando ricorsivamente le cartelle, se specificate nel filename e se non esistono. Ritorna: 0 -> Scrittura non effettuata 1 -> Scrittura effettuata Esempio (da console interattiva): >>> simpy._file.fwrite("prova","testo di prova") 1 >>> simpy._file.fwrite("prova","testo di prova, su un'altra riga","append") 1 >>> simpy._file.fwrite("prova","testo di prova, inserito fra le altre due","append@1") 1 >>> simpy._file.fwrite("prova", "testo di prova, in cima a tutti gli altri","top") 1 >>> simpy._file.fwrite("ho/creato/un/percorso/nuovo", "...e tutto funziona!") 1 >>> # Non ha i permessi per scrivere nella root dir >>> simpy._file.fwrite("/ho/creato/un/percorso/nuovo", "...e NON funziona!") 0 >>> simpy._file.fwrite("prova","testo di prova, che sostituisce la prima riga","replace@0") 1 >>> simpy._file.fwrite("prova",["testo di prova, che sostituisce la seconda riga", "testo di prova, che sostituisce la terza riga"],"replace@1:3") >>> 1 """ try: if mode is None: if len(filename.split("/")[0]) != 0: import os oldir = "" for dirs in range(len(filename.split("/"))-1): try: os.mkdir(oldir+filename.split("/")[dirs]) except OSError: dirs+1 oldir += filename.split("/")[dirs]+"/" self.handle = open(filename, "w") if type(text) is list: self.handle.writelines("\n".join(text)) else: self.handle.write(text) self.handle.close() return 1 else: if mode == "append": if self.check(filename) == 1: self.handle = open(filename, "a") self.handle.write("\n") if type(text) is list: self.handle.writelines("\n".join(text)) else: self.handle.write(text) self.handle.close() else: return 0 elif mode[:6] == "append" and len(mode.split("@")[0]) != 1: if self.check(filename) == 1: if mode.split("@")[1] == 0: self.fwrite(filename, text, "top") else: try: self.row = self.frow(filename, mode.split("@")[1]) if self.row is None: return 0 self.getlist = self.fstorage(filename) self.fdel(filename) self.fwrite(filename, self.getlist[:self.row]) self.fwrite(filename, text, "append") self.fwrite(filename, self.getlist[self.row:], "append") except ValueError: return 0 return 1 else: return 0 elif mode[:7] == "replace" and len(mode.split("@")[0]) != 1: if self.check(filename) == 1: self.rows = mode.split("@")[1] self.getlist = self.fstorage(filename) self.getrows = self.frow(filename, self.rows) if self.getrows == None: return 0 if type(self.getrows) is int and type(text) is not list: self.getlist[self.getrows] = text else: self.getlist[self.getrows[0]:self.getrows[1]] = text self.fdel(filename) self.fwrite(filename, self.getlist) return 1 else: return 0 elif mode == "top": if self.check(filename) == 1: self.handle = open(filename, "r") self.oldfilecontent = self.handle.read() self.handle.close() self.fdel(filename) self.fwrite(filename, text) self.fwrite(filename, self.oldfilecontent, "append") else: return 0 return 1 except IOError: return 0 def fdel(self, filename, row = None): """ Cancella l'intero file, o una o piu' righe Sintassi: simpy._file.fdel(filename[, righe]) "n" - Elimina la riga numero "n" del file "n:n2" - Elimina le righe selezionate in base al concetto slice di python. Per maggiori informazioni visita: http://it.diveintopython.org/getting_to_know_python/lists.html Ritorna: 0 -> Cancellazione non riuscita 1 -> Cancellazione riuscita Esempio (da console interattiva): >>> # Elimina l'ultima riga dal file >>> >>> simpy._file.fdel("prova",-1) 1 >>> simpy._file.check("/usr/lib/libsvg-cairo.a") 1 >>> # Elimina tutte le righe tranne la prima >>> simpy._file.fdel("prova","1:") 1 >>> simpy._file.fdel("prova") 1 >>> # Non ha i permessi necessari per la cancellazione >>> simpy._file.fdel("/usr/lib/libsvg-cairo.a") 0 """ import os try: if self.check(filename) == 1: if row == None: if len(filename.split(",")) != 1: for files in range(len(filename.split(","))): os.remove(filename.split(",")[files]) else: os.remove(filename) else: self.getlist = self.fstorage(filename) self.getrows = self.frow(filename, row) if self.getrows == None: return 0 if type(self.getrows) is int: del self.getlist[self.getrows] else: del self.getlist[self.getrows[0]:self.getrows[1]] self.fdel(filename) if len(self.getlist) != 0: self.fwrite(filename, self.getlist) return 1 else: return 0 except OSError,IOError: return 0 def fstorage(self, filename): """ Immagazina il file (riga per riga) in una lista. Sintassi: simpy._file.fstorage(filename) Ritorna: 0 -> Il file non esiste lista -> Il file esiste e la lista e' stata creata Esempio (da console interattiva): >>> simpy._file.fstorage("prova") ['riga 1', 'riga 2', 'riga 3'] >>> simpy._file.fstorage("una/dir/ed/un/file/inesistente") 0 >>> """ try: if self.check(filename) == 1: self.handle = open(filename, "r") self.filelist = self.handle.readlines() self.getlist = range(len(self.filelist)) for lists in self.getlist: lenght = len(self.filelist[lists]) if repr(self.filelist[lists][lenght-1:]) == repr("\n"): self.getlist[lists] = self.filelist[lists][:lenght-1] else: self.getlist[lists] = self.filelist[lists] return self.getlist else: return 0 except IOError: return 0 def frow(self, filename, row): """ Questa funzione verifica che il numero di riga/righe esista nel file specificato. Sintassi: simpy._file.frow(filename, numero) "n" - Verifica la riga numero "n" del file "n:n2" - Verifica le righe selezionate in base al concetto slice di python. Per maggiori informazioni visita: http://it.diveintopython.org/getting_to_know_python/lists.html Ritorna: None -> La/le riga/righe non esiste/esistono numero -> La riga selezionata esiste lista -> Le righe selezionate esistono Esempio (da console interattiva): >>> simpy._file.frow("prova", 1) 1 >>> simpy._file.frow("prova", "1:3") [1, 3] >>> # Ritorna None >>> simpy._file.frow("prova", 89) >>> """ if row == "": return 0 self.listfile = self.fstorage(filename) self.numrows = str(row).split(":") if len(self.numrows) == 1: try: myrow = int(row) self.listfile[myrow] return myrow except IndexError: return None else: try: self.first, self.second = None, None if len(self.numrows[0]) != 0: self.first = int(self.numrows[0]) try: self.listfile[self.first] except IndexError: return None if len(self.numrows[1]) != 0: self.second = int(self.numrows[1]) try: self.listfile[self.second] except IndexError: return None if self.first is None and self.second is None: return None except ValueError: return None return [self.first,self.second] # Istanziamo le classi _var = _var() # simpy._var _file = _file() # simpy._file