Foros del Web » Programando para Internet » Python »

Programa para eliminar todos los archivos vinculados a postgresql

Estas en el tema de Programa para eliminar todos los archivos vinculados a postgresql en el foro de Python en Foros del Web. Hice este programa para eliminar todos los archivos vinculados a postgresql debido a un problema con la instalación, pero evitando que borre los archivos python ...
  #1 (permalink)  
Antiguo 23/04/2011, 12:49
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Programa para eliminar todos los archivos vinculados a postgresql

Hice este programa para eliminar todos los archivos vinculados a postgresql debido a un problema con la instalación, pero evitando que borre los archivos python y los archivos dentro de la carpeta personal del sistema.

La pregunta es ¿Que se le puede agregar? para hacerlo más efectivo.

Código Python:
Ver original
  1. #/usr/bin/env python
  2.  
  3. """
  4. Desinstalador de postgresql
  5. """
  6. from os import remove, system
  7. from time import sleep
  8. from os.path import isdir, isfile
  9. import subprocess
  10.  
  11. def Deleteall(second_list_postgres_clean, firts_list_psql_clean):
  12.     obviados=0
  13.     eliminados=0
  14.     noexiste=0
  15.     for lista in (second_list_postgres_clean, firts_list_psql_clean):
  16.         for element in lista:
  17.             element=str(element)
  18.             if isdir(element) or isfile(element):
  19.                 print "Eliminando elemento " + element
  20.                 if element[0:12]=='/home/victor' or element[0:19]=='/usr/lib/pymodules/':
  21.                     print "Elemento obviado " + element
  22.                     obviados=obviados+1  
  23.                 else:
  24.                     sleep(1)
  25.                     #remove(element)
  26.                     print "Eliminado " + element
  27.                     eliminados=eliminados+1
  28.             else:
  29.                 print "El elemento no existe " + element
  30.                 noexiste=noexiste+1
  31.  
  32.     if isdir('/home/victor/.psql_history'):
  33.         print "Eliminacion forzada /home/victor/.psql_history"  
  34.         remove('/home/victor/.psql_history')
  35.         print "Eliminado"
  36.  
  37.     print "Todos los elementos fueron borrados"
  38.     print "Actualizando catalogo"
  39.     system('updatedb')
  40.     print "Elementos inexistentes " +str(noexiste)
  41.     print "Elementos obviados " +str(obviados)
  42.     print "Elementos Eliminados "+str(eliminados)
  43.     print "Actualizacion terminada, ejecucion terminada"
  44.  
  45. elements_psql_tuple=subprocess.Popen("/usr/bin/env locate "+ 'psql', shell=True, \
  46.                     stdout=subprocess.PIPE).communicate()
  47. string_to_clean=str(elements_psql_tuple)
  48.  
  49. firts_list_psql_clean=string_to_clean.replace("[","").replace("'","").replace("]","").replace("(","").replace(")","").split('\\n')
  50.  
  51. elements_postres_tuple=subprocess.Popen("/usr/bin/env locate "+ 'postgres', shell=True, \
  52.                     stdout=subprocess.PIPE).communicate()
  53.  
  54. string_to_clean=str(elements_postres_tuple)
  55.  
  56. second_list_postgres_clean=string_to_clean.replace("[","").replace("'","").replace("]","").replace("(","").replace(")","").split('\\n')
  57.  
  58. elements=second_list_postgres_clean.extend(firts_list_psql_clean)
  59.  
  60.  
  61. Deleteall(second_list_postgres_clean, firts_list_psql_clean)

Ahorita le estoy agregando manejo de archivos para crear un log con los archivos borrados, los obviados, y los que estaban inexistentes. Lo agregare también al terminar.
  #2 (permalink)  
Antiguo 23/04/2011, 13:23
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Programa para eliminar todos los archivos vinculados a postgresql

Preferentemente dado que es ubuntu siempre es recomendable usar el administrador de paquetes (apt-get)
  #3 (permalink)  
Antiguo 23/04/2011, 14:28
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Respuesta: Programa para eliminar todos los archivos vinculados a postgresql

Si, razpetia. Lo malo es que dañe esto mucho con demasiado y pregunte en el foro de postgresql y me dijeron borra todo lo que tenga que ver con el y vuelvelo a instalar.
  #4 (permalink)  
Antiguo 23/04/2011, 15:18
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Programa para eliminar todos los archivos vinculados a postgresql

Código:
apt-get remove --purge <PackageName>
Así lo limpias todo.
  #5 (permalink)  
Antiguo 23/04/2011, 15:44
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Respuesta: Programa para eliminar todos los archivos vinculados a postgresql

Cita:
Iniciado por razpeitia Ver Mensaje
Código:
apt-get remove --purge <PackageName>
Así lo limpias todo.
Use aptitude purge <PackageName>

Y sin embargo no quiso funcionar. Si supieras que ya corrí el programita y en mi caso particular funcionó perfectamente.

Por si alguien lo llega a necesitar, pero no me hago responsable de lo que suceda.

Hay que hacer modificaciones a linea

Código Python:
Ver original
  1. element[0:12]=='/home/victor' or element[0:19]=='/usr/lib/pymodules/':

por la carpeta del nombre de usuario, modificando también el rango de la cadena elemento.

Código Python:
Ver original
  1. #/usr/bin/env python
  2.  
  3. """
  4. By aka SamuraiBlanco
  5.  
  6. GPL(V3)
  7.  
  8. This program is free software: you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation, either version 3 of the License, or
  11. (at your option) any later version.
  12.  
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with this program.  If not, see <http://www.gnu.org/licenses/>
  20. """
  21. from os import remove, system, getcwd, mkdir
  22. from time import sleep
  23. from os.path import isdir, isfile, join
  24. import subprocess
  25.  
  26.  
  27.  
  28. def makelogs(list_noexiste, list_obviados, list_eliminados):
  29.     Dictionary={'not_found':list_noexiste, 'passed':list_obviados, 'deleted':list_eliminados}
  30.     actions={'not_found':'que no existieron', 'passed':'obviados', 'deleted':'eliminados'}
  31.     for x in Dictionary.keys():
  32.         if isfile(join(getcwd(),'postgresql_delete_logs','log_'+x+'.txt'))==False:
  33.            Log=open(join(getcwd(),'postgresql_delete_logs','log_'+x+'.txt'),'w')
  34.            Log.write('Estos son los archivos $action en la ejecucion: \n'.replace("$action", actions[x]))
  35.            for archivo in Dictionary[x]:
  36.                Log.write(archivo + '\n')
  37.            Log.close()
  38.         else:
  39.            Log=open(join(getcwd(),'postgresql_delete_logs','log_'+x+'.txt'),'a')
  40.            for archivo in Dictionary[x]:
  41.                Log.write(archivo + '\n')
  42.            Log.close()
  43.     return
  44.  
  45. def Deleteall(second_list_postgres_clean, firts_list_psql_clean):
  46.     print "Removiendo paquetes obsoletos con aptitude clean"
  47.     print "\n \n \n \n"
  48.     system('aptitude clean')
  49.     print "\n \n \n \n"
  50.     print "Comienza la eliminacion... en tres segundos \n \n"
  51.     sleep(1)
  52.     print "Comienza la eliminacion... en dos segundos \n \n"    
  53.     sleep(1)
  54.     print "Comienza la eliminacion... en un segundo \n \n"
  55.     sleep(1)
  56.     nobviados=0
  57.     neliminados=0
  58.     nnoexiste=0
  59.     list_eliminados=[]
  60.     list_obviados=[]
  61.     list_noexiste=[]
  62.     for lista in (second_list_postgres_clean, firts_list_psql_clean):
  63.         for element in lista:
  64.             element=str(element)
  65.             if isdir(element) or isfile(element):
  66.                 print "Eliminando elemento " + element
  67.                 if element[0:12]=='/home/victor' or element[0:19]=='/usr/lib/pymodules/':
  68.                     print "Elemento obviado " + element
  69.                     nobviados=nobviados+1
  70.                     list_obviados.append(element)
  71.                 else:
  72.                     sleep(1)
  73.                     if isdir(element):
  74.                         system('rm -rf ' +element)
  75.                     elif isfile(element):    
  76.                         remove(element)
  77.                     print "Eliminado " + element
  78.                     neliminados=neliminados+1
  79.                     list_eliminados.append(element)
  80.             else:
  81.                 print "El elemento no existe " + element
  82.                 nnoexiste=nnoexiste+1
  83.                 list_noexiste.append(element)
  84.  
  85.     if isdir('/home/victor/.psql_history'):
  86.         print "Eliminacion forzada /home/victor/.psql_history"  
  87.         remove('/home/victor/.psql_history')
  88.         print "Eliminado"
  89.  
  90.     print "Todos los elementos fueron borrados"
  91.     print "Actualizando catalogo, espere por favor, esto puede tomar algunos minutos"
  92.     system('updatedb')
  93.     print "Elementos inexistentes " +str(nnoexiste)      
  94.     print "Elementos obviados " +str(nobviados)
  95.     print "Elementos Eliminados "+str(neliminados)
  96.     print "Puede revisar los logs en " + join(getcwd(),'postgresql_delete_logs')
  97.     if isdir(join(getcwd(),'postgresql_delete_logs'))==False:
  98.         mkdir('postgresql_delete_logs')
  99.         makelogs(list_noexiste, list_obviados, list_eliminados)
  100.     else:
  101.         makelogs(list_noexiste, list_obviados, list_eliminados)        
  102.     print "Actualizacion terminada, ejecucion terminada"
  103.  
  104. print """ \n\n\n\n\n This program is free software: you can redistribute it and/or modify
  105.    it under the terms of the GNU General Public License as published by
  106.    the Free Software Foundation, either version 3 of the License, or
  107.    (at your option) any later version.
  108.  
  109.    This program is distributed in the hope that it will be useful,
  110.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  111.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  112.    GNU General Public License for more details.
  113.  
  114.    You should have received a copy of the GNU General Public License
  115.    along with this program.  If not, see <http://www.gnu.org/licenses/>
  116.    \n\n\n\n\n
  117.    """
  118.  
  119. print "Buen dia, este es un script para eliminar una instalacion \
  120.       \n corrupta de postgresql\n\n"
  121.  
  122. control=raw_input('Introduzca 1 para continuar, cualquier otra tecla para salir: ')
  123.  
  124. if control==" ":
  125.     print "Saliendo"
  126.  
  127. control=int(control)
  128.  
  129. if control==1:
  130.     print "\n\nComienza adquisicion de datos, esto puede tardar algunos segundos..."    
  131.     elements_psql_tuple=subprocess.Popen("/usr/bin/env locate "+ 'psql', shell=True, \
  132.                     stdout=subprocess.PIPE).communicate()
  133.     string_to_clean=str(elements_psql_tuple)
  134.  
  135.     firts_list_psql_clean=string_to_clean.replace("[","").replace("'","").replace("]","").replace("(","").replace   (")","").split('\\n')
  136.  
  137.     elements_postres_tuple=subprocess.Popen("/usr/bin/env locate "+ 'postgres', shell=True, \
  138.                     stdout=subprocess.PIPE).communicate()
  139.  
  140.     string_to_clean=str(elements_postres_tuple)
  141.  
  142.     second_list_postgres_clean=string_to_clean.replace("[","").replace("'","").replace("]","").replace("(","").replace(")","").split('\\n')
  143.  
  144.     elements=second_list_postgres_clean.extend(firts_list_psql_clean)
  145.    
  146.     Deleteall(second_list_postgres_clean, firts_list_psql_clean)
  147. else:
  148.     print "Saliendo"

Etiquetas: instalación, libreria, linux, os.system, postgresql, subproces, ubuntu
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:54.