Created
March 18, 2024 14:06
-
-
Save pwqw/6619e0eb479fd0fb1a103d97bd82bc11 to your computer and use it in GitHub Desktop.
Instalar diferentes versiones de python en entorno Debian-like
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import tarfile | |
import tempfile | |
from urllib import request | |
PYTHON_VERSION = input('Ingrese la version de python a instalar [3.9]: ') | |
if PYTHON_VERSION == '': | |
PYTHON_VERSION = '3.9' | |
print('Verificando dependencias...') | |
try: | |
# obtener la lista de paquetes | |
packages = os.popen('apt list --installed').read() | |
packages = packages.split('\n') | |
packages = [x.split('/')[0] for x in packages if '/' in x] | |
# verificar las dependencias | |
dependencies = [ | |
'build-essential', | |
'curl', | |
] | |
not_installed = [x for x in dependencies if x not in packages] | |
# informar | |
if len(not_installed) > 0: | |
print('Los siguientes paquetes no estan instalados:') | |
for package in not_installed: | |
print(package) | |
# instalar los paquetes | |
print('Instalando paquetes...') | |
os.system('apt install ' + ' '.join(not_installed)) | |
else: | |
print('Todas las dependencias estan instaladas.') | |
except Exception as e: | |
print(f"Failed to verify dependencies: {e}") | |
exit(1) | |
url = 'https://www.python.org/ftp/python/' | |
response = request.urlopen(url) | |
html = response.read() | |
lista = html.decode('utf-8').split() # obtener los tags | |
lista = [x for x in lista if 'href' in x] # filtrar los href | |
lista = [x for x in lista if f'{PYTHON_VERSION}.' in x] # filtrar las versiones PYTHON_VERSION [3.9] | |
lista = [x.split('"')[1] for x in lista] # separar por comillas y obtener el segundo elemento (la ruta) | |
lista = [x.replace('/', '') for x in lista] # quitar la barra del final | |
# obtener la version mayor teniendo en cuenta que sort() no ordena bien los numeros con puntos | |
version_mayor = None | |
for v in lista: | |
if version_mayor is None: | |
version_mayor = v | |
elif int(v.split('.')[2]) > int(version_mayor.split('.')[2]): | |
version_mayor = v | |
print('Version mayor: ' + version_mayor) | |
url = f'https://www.python.org/ftp/python/{version_mayor}/Python-{version_mayor}.tar.xz' | |
# descargar el archivo | |
print('Descargando archivo...') | |
try: | |
response = request.urlopen(url) | |
file_size = int(response.headers['Content-Length']) | |
chunk_size = 1024 | |
num_bars = file_size // chunk_size | |
downloaded = 0 | |
# crear un temporary file para escribir el archivo descargado | |
temp_file = tempfile.NamedTemporaryFile(delete=False) | |
# mostrar el progreso de la descarga | |
while True: | |
chunk = response.read(chunk_size) | |
if not chunk: | |
break | |
temp_file.write(chunk) | |
downloaded += len(chunk) | |
progress = int(downloaded / file_size * 100) | |
sys.stdout.write(f"\rProgreso: {progress}%") | |
sys.stdout.flush() | |
# cerrar el temporary file | |
temp_file.close() | |
print("\nDescarga completada.") | |
except Exception as e: | |
print(f"Failed to download file: {e}") | |
exit(1) | |
# Descomprimir el archivo desde el temporary file | |
print('Descomprimiendo archivo...') | |
try: | |
with tarfile.open(temp_file.name, mode='r:xz') as tar: | |
tar.extractall() | |
except Exception as e: | |
print(f"Failed to extract file: {e}") | |
exit(1) | |
print('Archivo descomprimido exitosamente.') | |
# Instalar python | |
print('Instalando python...') | |
try: | |
# cambiar al directorio descomprimido | |
temp_dir = f'Python-{version_mayor}' | |
os.chdir(temp_dir) | |
# instalar python | |
os.system('./configure --enable-optimizations') | |
os.system('make -j 4') | |
os.system('make altinstall') | |
# volver al directorio anterior | |
os.chdir('..') | |
except Exception as e: | |
print(f"Failed to install python: {e}") | |
exit(1) | |
# verificar la instalacion | |
print('Verificando la instalacion...') | |
try: | |
os.system(f'python{PYTHON_VERSION} --version') | |
print('Instalacion exitosa.') | |
except Exception as e: | |
print(f"Failed to verify installation: {e}") | |
exit(1) | |
# borrar el directorio temp_dir pidiendo confirmacion | |
temp_dir = f'Python-{version_mayor}' | |
resp = input(f'¿Desea eliminar el directorio {temp_dir}? [S/n]') | |
if resp in ['S', 's', '']: | |
os.system(f'rm -rf {temp_dir}') | |
print(f'Directorio {temp_dir} eliminado.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment