Introduction
This guide shows you how to set up your Python project in Codespaces. It will take you through an example of opening your project in a codespace, and adding and modifying a dev container configuration from a template.
Prerequisites
- You should have an existing Python project in a repository on GitHub.com. If you don't have a project, you can try this tutorial with the following example: https://github.com/2percentsilk/python-quickstart.
- You must have Codespaces enabled for your organization.
Step 1: Open your project in a codespace
-
Under the repository name, use the Code drop-down menu, and in the Codespaces tab, click Create codespace on main.
If you don’t see this option, Codespaces isn't available for your project. See Access to Codespaces for more information.
When you create a codespace, your project is created on a remote VM that is dedicated to you. By default, the container for your codespace has many languages and runtimes including Node.js, JavaScript, Typescript, nvm, npm, and yarn. It also includes a common set of tools like git, wget, rsync, openssh, and nano.
Puedes personalizar tu codespace si ajustas la cantidad de vCPU y RAM, agregando dotfiles para personalizar tu ambiente o modificando las herramientas y scripts instalados.
Codespaces uses a file called devcontainer.json
to configure the development container that you use when you work in a codespace. Each repository can contain one or more devcontainer.json
files, to give you exactly the development environment you need to work on your code in a codespace.
On launch, Codespaces uses a devcontainer.json
file, and any dependent files that make up the dev container configuration, to install tools and runtimes, and perform other setup tasks that the project requires. Para obtener más información, consulta la sección "Introducción a los contenedores dev".
Step 2: Add a dev container configuration to your repository from a template
The default development container, or "dev container," for Acerca de GitHub Codespaces comes with the latest Python version, package managers (pip, Miniconda), and other common tools preinstalled. However, we recommend that you configure your own dev container to include all of the tools and scripts that your project needs. This will ensure a fully reproducible environment for all Acerca de GitHub Codespaces users in your repository.
To set up your repository to use a custom dev container, you will need to create one or more devcontainer.json
files. You can add these either from a template, in Visual Studio Code, or you can write your own. For more information on dev container configurations, see "Introduction to dev containers".
-
Accede a la Paleta de comandos de Visual Studio Code (Shift+Command+P (Mac) / Ctrl+Shift+P (Windows/Linux)) y comienza a escribir "dev container". Selecciona Codespaces: Agregar archivos de configuración del contenedor de desarrollo....
-
For this example, click Python 3. If you need additional features you can select any container that’s specific to Python or a combination of tools such as Python 3 and PostgreSQL.
-
Click the recommended version of Python.
-
Accept the default option to add Node.js to your customization.
-
Accede a la Paleta de comandos de Visual Studio Code (Shift + Command + P / Ctrl + Shift + P) y comienza a escribir "rebuild". Selecciona Codespaces: Reconstruir contenedor.
Anatomy of your dev container
Adding the Python dev container template adds a .devcontainer
directory to the root of your project's repository with the following files:
devcontainer.json
- Dockerfile
The newly added devcontainer.json
file defines a few properties that are described after the sample.
devcontainer.json
{
"name": "Python 3",
"build": {
"dockerfile": "Dockerfile",
"context": "..",
"args": {
// Update 'VARIANT' to pick a Python version: 3, 3.6, 3.7, 3.8, 3.9
"VARIANT": "3",
// Options
"INSTALL_NODE": "true",
"NODE_VERSION": "lts/*"
}
},
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"python.pythonPath": "/usr/local/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
"python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
"python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
"python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
"python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
"python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
"python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
"python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"ms-python.python"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "pip3 install --user -r requirements.txt",
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}
- name - You can name our dev container anything, this is just the default.
- build - The build properties.
- dockerfile - In the
build
object,dockerfile
contains the path to the Dockerfile that was also added from the template. - args
- variant: This file only contains one build argument, which is the node variant we want to use that is passed into the Dockerfile.
- dockerfile - In the
- settings - These are Visual Studio Code settings.
- terminal.integrated.shell.linux - While bash is the default here, you could use other terminal shells by modifying this.
- extensions - These are extensions included by default.
- ms-python.python - The Microsoft Python extension provides rich support for the Python language (for all actively supported versions of the language: >=3.6), including features such as IntelliSense, linting, debugging, code navigation, code formatting, refactoring, variable explorer, test explorer, and more.
- forwardPorts - Any ports listed here will be forwarded automatically. For more information, see "Forwarding ports in your codespace."
- postCreateCommand - Use this to run commands that aren't defined in the Dockerfile, like
pip3 install -r requirements
, after your codespace is created. - remoteUser - By default, you’re running as the
vscode
user, but you can optionally set this toroot
.
Dockerfile
# [Choice] Python version: 3, 3.9, 3.8, 3.7, 3.6
ARG VARIANT="3"
FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT}
# [Option] Install Node.js
ARG INSTALL_NODE="true"
ARG NODE_VERSION="lts/*"
RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
# COPY requirements.txt /tmp/pip-tmp/
# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
# && rm -rf /tmp/pip-tmp
# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
# [Optional] Uncomment this line to install global node packages.
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1
You can use the Dockerfile to add additional container layers to specify OS packages, node versions, or global packages we want included in our container.
Step 3: Modify your devcontainer.json file
With your dev container configuration added and a basic understanding of what everything does, you can now make changes to customize your environment further. In this example, you'll add properties to install extensions and your project dependencies when your codespace launches.
-
In the Explorer, expand the
.devcontainer
folder and select thedevcontainer.json
file from the tree to open it. -
Update the
extensions
list in yourdevcontainer.json
file to add a few extensions that are useful when working with your project.JSON "extensions": [ "ms-python.python", "cstrap.flask-snippets", "streetsidesoftware.code-spell-checker" ],
-
Uncomment the
postCreateCommand
to auto-install requirements as part of the codespaces setup process.JSON // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "pip3 install --user -r requirements.txt",
-
Accede a la Paleta de comandos de Visual Studio Code (Shift + Command + P / Ctrl + Shift + P) y comienza a escribir "rebuild". Selecciona Codespaces: Reconstruir contenedor.
Reconstruir dentro de tu codespace garantiza que tus cambios funcionan como se espera antes de que confirmes los cambios en el repositorio. Si algo resulta en un fallo, se te colocará en un codespace con un contenedor de recuperación desde el cual puedes reconstruir para seguir ajustando tu contenedor.
-
Check your changes were successfully applied by verifying the Code Spell Checker and Flask Snippet extensions were installed.
Step 4: Run your application
In the previous section, you used the postCreateCommand
to install a set of packages via pip3. With your dependencies now installed, you can run your application.
-
Run your application by pressing
F5
or enteringpython -m flask run
in the codespace terminal. -
When your project starts, you should see a toast in the bottom right corner with a prompt to connect to the port your project uses.
Step 5: Commit your changes
Una vez que hayas hecho cambios a tu codespace, ya sea de código nuevo o de cambios de configuración, necesitarás confirmar tus cambios. El confirmar los cambios en tu repositorio garantiza que cualquiera que cree un codespace desde este repositorio tendrá la misma configuración. Esto también significa que cualquier personalización que hagas, tal como agregar extensiones de VS Code, aparecerá para todos los usuarios.
Para obtener más información, consulta la sección "Utilizar el control de código fuente en tu codespace"
Next steps
You should now be ready start developing your Python project in Codespaces. Here are some additional resources for more advanced scenarios.