Using Python in Windows WSL: A Detailed Guide
With Windows Subsystem for Linux (WSL), you can run a Linux distribution alongside your Windows installation, allowing you to enjoy the best of both worlds. This guide will walk you through the process of setting up WSL, installing Python, and running Python scripts in a WSL environment.
Prerequisites
Before starting, ensure you have:
- A Windows 10 (version 2004 and higher) or Windows 11 system.
- Basic knowledge of command-line interfaces.
Step 1: Installing WSL
First, you need to install WSL on your Windows machine. Follow these steps:
Open PowerShell as Administrator:
Press
Win + X
and selectWindows PowerShell (Admin)
.Enable WSL:
1
wsl --install
This command will enable the necessary features and install a default Linux distribution (usually Ubuntu). Restart your computer if prompted.
Verify Installation:
After restarting, open a new PowerShell window and check the WSL version:
1
wsl -l -v
You should see your installed Linux distribution listed.
Step 2: Setting Up a Linux Distribution
If you installed the default Ubuntu distribution, you can proceed with setting it up. If you want to install a different distribution, follow these steps:
List Available Distributions:
1
wsl --list --online
Install a Distribution:
1
wsl --install -d <DistributionName>
Replace
<DistributionName>
with the name of the distribution you want to install.Launch and Set Up the Distribution:
Open your installed distribution from the Start menu or by typing
wsl
in PowerShell. Follow the on-screen instructions to set up your username and password.
Step 3: Installing Python
Now that you have your Linux distribution set up, you can install Python.
Update Package List:
Open your WSL terminal and run:
1
sudo apt update
Install Python:
1
sudo apt install python3 python3-pip
Verify Installation:
Check the installed Python version:
1
python3 --version
Step 4: Running a Python Script
Let’s create and run a simple Python script to ensure everything is working correctly.
Create a Python Script:
In your WSL terminal, create a new file:
1
nano hello.py
Add the following content:
1
print("Hello, WSL!")
Save and exit the editor (
Ctrl + X
, thenY
, thenEnter
).Run the Script:
Execute the script using Python:
1
python3 hello.py
You should see the output
Hello, WSL!
.
Conclusion
By following this guide, you’ve set up WSL on your Windows machine, installed a Linux distribution, and successfully installed and run Python. This setup allows you to leverage the power of Linux development tools while working within your Windows environment. Explore further by installing additional Python packages, setting up virtual environments, and developing your projects in this flexible setup.