Python – instalación y configuración en Ubuntu

Recomiendo ver antes – instalacion de Homebrew y asdf en ubuntu ( es corto son 5 comandos)

📘 Documentación Oficial

Python – Docu
Python – On DevDocs.io

⭐ Frameworks Populares (ordenado de menor a mayor curva)

Flas…


This content originally appeared on DEV Community and was authored by Oscar Pincho

Python - logo

Recomiendo ver antes - instalacion de Homebrew y asdf en ubuntu ( es corto son 5 comandos)

📘 Documentación Oficial

Python - Docu
Python - On DevDocs.io

⭐ Frameworks Populares (ordenado de menor a mayor curva)

  • Flask — Minimalista, simple.
  • FastAPI — Muy rápido, moderno.
  • Django — Completo y estructurado.

🛠️ Instalación de Python en Ubuntu

sudo apt update
sudo apt install python3 python3-pip

🍺 Instalación con Homebrew

brew install python

📦 Gestor de Paquetes Estándar (pip — viene incluido)

Consultar versión:

pip3 --version

Instalar un paquete:

pip install <paquete>

🔧 Instalación con ASDF

Dependencias del sistema

sudo apt update
sudo apt install -y build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev

Instalar plugin + versión

asdf plugin add python
asdf list-all python

# instalar distintas versiones
asdf install python 3.12.2
asdf install python 2.7.18

# Configurar una version global
asdf global python 3.12.2

# Configurar una version Local
# - Recuerda que una version localsolo afecta al directorioactual que contenga el archivo .tool-versions
asdf local python 2.7.18

Ejemplo: .tool-versions

python 3.12.2

📝▶️ Crear y ejecutar un archivo Python

Crear archivo:

touch hola.py

Contenido de hola.py

print("Hola Mundo desde Python!")

💻 Ejecutar Localmente:

python3 hola.py

quieres saber mas?

🟦 Ejemplo básico en Python

🗂️🌐 Servidor Web de archivos estáticos.

Nota: Python ya trae un servidor web básico integrado. No necesitas instalar nada.

Que Hace:

  1. Definir el nombre del parámetro de consulta (query parameter)
  2. Obtener el valor del parámetro de consulta de la URL.
    • strip_html_tags(text):Elimina etiquetas HTML dejando solo el contenido interior.
  3. Se dibuja la variable recivida en el query parameter dentro de la etiqueta

📝 Crear archivo: touch index.py

📦 Contenido de index.py

import re
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Obtener parámetros desde la URL
        parsed = urllib.parse.urlparse(self.path)
        query = urllib.parse.parse_qs(parsed.query)

        username = query.get("username", ["invitado"])[0]
        username = strip_html_tags(username)

        # Respuesta
        content = f"""
        <!DOCTYPE html>
        <html lang="es">
        <head>
            <meta charset="UTF-8">
            <title>Hola</title>
        </head>
        <body style="text-align:center">
            <h1>Hola, {username}</h1>
        </body>
        </html>
        """

        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(content.encode("utf-8"))



def strip_html_tags(text):
    return re.sub(r"<[^>]+>", "", text)


# Levantar servidor
if __name__ == "__main__":
    server = HTTPServer(("localhost", 7000), Handler)
    print("Servidor corriendo en http://localhost:7000")
    print("Prueva en http://localhost:7000?username=Homero")
    server.serve_forever()

▶️ Correr el proyecto / levantar el servidor

python3 index.py

👉 visitar:
http://localhost:7000/?username=Homero

⚙️🧩 Json API Rest

Que Hace:

  1. Lee los datos desde un archivo data.json
  2. expones 1 endpoint con esos datos
    • Una Lista de personajes en /characters
    • y los datos de un personaje por id /characters/:id

Ejemplo de archivo: data.json

[
  {
    "id": 1,
    "age": 39,
    "name": "Homer Tompson",
    "portrait_path": "https://cdn.thesimpsonsapi.com/500/character/1.webp"
  },
  {
    "id": 2,
    "age": 39,
    "name": "Marge Simpson",
    "portrait_path": "https://cdn.thesimpsonsapi.com/500/character/2.webp"
  }
]

📝 Crear archivo: touch api.py

▶️ Contenido del archivo: api.py

import json
from http.server import BaseHTTPRequestHandler, HTTPServer

# Cargar data.json
def load_characters():
    with open("data.json", "r", encoding="utf-8") as f:
        return json.load(f)


class MyHandler(BaseHTTPRequestHandler):

    def _send_json(self, data, status=200):
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(data, ensure_ascii=False).encode("utf-8"))

    def do_GET(self):
        characters = load_characters()

        # GET /characters
        if self.path == "/characters":
            self._send_json(characters)
            return

        # GET /characters/:id
        if self.path.startswith("/characters/"):
            try:
                id_str = self.path.split("/")[2]
                char_id = int(id_str)
            except:
                self._send_json({"error": "ID inválido"}, 400)
                return

            found = next((c for c in characters if c["id"] == char_id), None)

            if found:
                self._send_json(found)
                return
            else:
                self._send_json({"error": "Personaje no encontrado"}, 404)
                return

        # Si no coincide ninguna ruta
        self._send_json({
            "error": "Ruta no encontrada",
            "url_lista": "http://localhost:7001/characters",
            "url_personaje": "http://localhost:7001/characters/1"
        }, 404)


if __name__ == "__main__":
    server = HTTPServer(("localhost", 7001), MyHandler)
    print("Servidor corriendo en http://localhost:7001/characters")
    server.serve_forever()

▶️ Correr el proyecto / levantar el servidor

python3 api.js

👉 visitar:
http://localhost:7001/characters

Para probar el sanitizado de url:
http://localhost:7001/characters/1


This content originally appeared on DEV Community and was authored by Oscar Pincho


Print Share Comment Cite Upload Translate Updates
APA

Oscar Pincho | Sciencx (2025-11-30T16:00:00+00:00) Python – instalación y configuración en Ubuntu. Retrieved from https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/

MLA
" » Python – instalación y configuración en Ubuntu." Oscar Pincho | Sciencx - Sunday November 30, 2025, https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/
HARVARD
Oscar Pincho | Sciencx Sunday November 30, 2025 » Python – instalación y configuración en Ubuntu., viewed ,<https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/>
VANCOUVER
Oscar Pincho | Sciencx - » Python – instalación y configuración en Ubuntu. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/
CHICAGO
" » Python – instalación y configuración en Ubuntu." Oscar Pincho | Sciencx - Accessed . https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/
IEEE
" » Python – instalación y configuración en Ubuntu." Oscar Pincho | Sciencx [Online]. Available: https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/. [Accessed: ]
rf:citation
» Python – instalación y configuración en Ubuntu | Oscar Pincho | Sciencx | https://www.scien.cx/2025/11/30/python-instalacion-y-configuracion-en-ubuntu/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.