Hello there! If you’re embarking on your software development journey with Python, especially on Ubuntu, having a professional and well-organized working environment is crucial. It not only boosts your productivity but also helps you avoid many headaches related to library or Python version management down the line.
When I first switched from CentOS to Ubuntu, I spent a whole week fumbling around getting familiar with the package management system. `apt` is powerful, but installing and managing multiple Python versions and libraries without conflicts between different projects was truly a pain.
I remember once accidentally installing a library for Project A, and suddenly Project B, which was running smoothly, broke, simply because they shared the same system Python environment. These experiences helped me realize the importance of an isolated and tightly managed development environment.
In this article, I’ll guide you through setting up a ‘best-in-class’ toolkit. This trio includes VS Code as your IDE, Poetry for managing packages and virtual environments, and Jupyter for those working with data or needing an interactive environment. I believe this set of tools will help you elevate your Python development work.
Core Concepts: Why VS Code, Poetry, and Jupyter?
Before we dive into the practical steps, let’s explore why this trio is an ideal choice for a professional Python development environment.
VS Code: The Heart of Every Project
Visual Studio Code (VS Code) is more than just a source code editor. Thanks to its vast marketplace of extensions, VS Code easily transforms into a powerful IDE (Integrated Development Environment).
It supports almost every programming language, excelling particularly with Python. VS Code offers an integrated debugger, an in-window terminal, code autocompletion, linting, and many other useful features. For Python, extensions like Python and Pylance provide a smooth, professional development experience.
Poetry: The Solution to Dependency Hell
Have you ever encountered a situation where one project requires library X version 1.0, but another project demands X version 2.0? That’s precisely “Dependency Hell.” Previously, we often used pip and venv to create virtual environments.
However, Poetry goes far beyond that. Poetry not only creates virtual environments but also manages the entire lifecycle of a Python project. It helps declare dependencies explicitly, install packages, package libraries, and publish them. This ensures the consistency and reproducibility of your environment, making it easy to share projects with colleagues without worrying about minor issues.
Jupyter: An Interactive Playground for Data and Ideas
Jupyter Notebook (or JupyterLab) is an indispensable tool for data scientists, machine learning engineers, or anyone who wants to experiment with code quickly and visually. It allows you to combine code, descriptive text (markdown), mathematical formulas, and charts within a single interactive document. With Jupyter, you can run individual code blocks, see results instantly, and easily present your ideas. Integrating Jupyter into VS Code makes this experience even more seamless.
Detailed Practice: Building Your Environment
Now it’s time to get started. I’ll guide you step-by-step through setting up a complete environment.
1. Prepare Your Ubuntu System
First, ensure your Ubuntu system is updated and has all the necessary tools.
sudo apt update
sudo apt upgrade -y
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 libffi-dev liblzma-dev
These packages are essential for compiling Python from source, a critical step if you want to manage multiple Python versions.
2. Install and Manage Python Versions with pyenv
While Ubuntu comes with Python pre-installed, managing multiple Python versions for different projects is more efficient with `pyenv`. This is the tool I often use to avoid version conflicts.
Install pyenv:
curl https://pyenv.run | bash
After running the command, you need to add the following lines to your shell configuration file (usually `~/.bashrc` or `~/.zshrc`). Open the file using `nano` or `vim`:
export PYENV_ROOT="$HOME/.pyenv"
command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
Save the file and then reload your shell configuration:
source ~/.bashrc
Install a specific Python version:
For example, to install Python 3.10.12:
pyenv install 3.10.12
pyenv global 3.10.12
The `pyenv global` command will set this version as the default for your entire system (within the `pyenv` context). To verify:
python --version
It should display `Python 3.10.12`.
3. Install VS Code
The simplest way to install VS Code on Ubuntu is using Snap:
sudo snap install --classic code
After installation, you can open VS Code from your applications menu or by typing `code` in the terminal.
Install Essential Extensions:
In VS Code, go to the Extensions view (the square icon on the left sidebar) and search for and install the following extensions:
- Python (Microsoft): Provides basic Python support.
- Pylance (Microsoft): Offers powerful language support (autocompletion, type checking).
- Jupyter (Microsoft): Supports Jupyter Notebooks and JupyterLab.
4. Install Poetry
Poetry has its own convenient installation script:
curl -sSL https://install.python-poetry.org | python3 -
After installation, you need to add Poetry to your PATH environment variable. Typically, the script will suggest the path. You just need to add it to `~/.bashrc` (or `~/.zshrc`) similar to `pyenv`:
export PATH="$HOME/.local/bin:$PATH"
Then, `source ~/.bashrc` to update the PATH. Check the Poetry version:
poetry --version
One important setting I highly recommend is configuring Poetry to create virtual environments directly within the project directory. This will make it easier to manage and move your projects:
poetry config virtualenvs.in-project true
5. Set Up a Python Project with Poetry and VS Code
Now, let’s create a new project and use Poetry to manage it.
mkdir my_python_project
cd my_python_project
poetry init
`poetry init` will ask you for some project information (name, version, author, description, license…). You can press Enter to accept the default values or fill in your own information. After this step, Poetry will create the `pyproject.toml` file.
Add a library package to the project, for example `requests`:
poetry add requests
Poetry will automatically create a virtual environment (in the .venv directory if you’ve configured virtualenvs.in-project true). Then, it will install requests along with its dependencies, and update the pyproject.toml and poetry.lock files.
Open this project in VS Code:
code .
In VS Code, you need to select the correct Python interpreter for the virtual environment created by Poetry. To do this, press Ctrl+Shift+P (or Cmd+Shift+P on macOS) to open the command palette. Type “Python: Select Interpreter”, then choose the path to the python executable within your project’s .venv directory (e.g., ./.venv/bin/python).
Create a main.py file and test it:
# main.py
import requests
def fetch_data(url):
try:
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching data from {url}: {e}")
return None
if __name__ == "__main__":
api_url = "https://jsonplaceholder.typicode.com/todos/1"
data = fetch_data(api_url)
if data:
print("Data fetched successfully:")
print(data)
else:
print("Could not fetch data.")
Run this file from the integrated terminal in VS Code (or using poetry run python main.py):
poetry run python main.py
You will see the results from the API printed out.
6. Use Jupyter Notebook with Poetry and VS Code
To use Jupyter within your Poetry environment, you need to install the jupyter package into it:
poetry add jupyter
After installation, create a new file in VS Code named notebook.ipynb. VS Code will automatically recognize and open it as a Jupyter Notebook. Ensure you have selected the correct kernel, which should be your project’s Poetry environment (usually displayed in the upper-right corner of the Notebook).
Try adding a few code cells:
# Cell 1
import pandas as pd
import numpy as np
data = {
'A': np.random.rand(5),
'B': np.random.randint(1, 10, 5)
}
df = pd.DataFrame(data)
print(df)
# Cell 2
# Plot a simple chart
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 4))
plt.plot(df['A'], label='Column A')
plt.plot(df['B'], label='Column B')
plt.title('Sample Data')
plt.xlabel('Index')
plt.ylabel('Value')
plt.legend()
plt.grid(True)
plt.show()
Run each cell one by one and view the results directly in the Notebook.
Conclusion
Setting up a professional Python development environment on Ubuntu with VS Code, Poetry, and Jupyter is more than just an option; it’s a worthwhile investment in your productivity and project stability. With VS Code, you gain a powerful IDE. Poetry helps you thoroughly address package and virtual environment management issues. And Jupyter is an excellent tool for experimenting, analyzing, and presenting data.
I believe that with this setup, you’ll be able to focus entirely on writing code and solving problems, rather than getting bogged down by environmental complexities. Give it a try and experience the difference it makes to your workflow!
