Linux Python

Chapter 6.1 : Installing Python and Running Python Scripts in WSL Ubuntu

Chapter 6.1: Installing Python and Running Python Programs in WSL Ubuntu

Python is a powerful and beginner-friendly programming language used in automation, data science, web development, and more. WSL Ubuntu provides a seamless way to install and run Python on your Windows system.

In this chapter, you’ll learn how to install Python, run Python scripts, and manage Python packages using pip in WSL Ubuntu.

๐Ÿ Check If Python is Already Installed

python3 --version

If installed, you’ll see something like:

Python 3.10.12

๐Ÿ“ฅ Installing Python and pip

If Python is not installed or you want to update it, follow these steps:

๐Ÿ“Œ Update Package List

sudo apt update

๐Ÿ“Œ Install Python and pip

sudo apt install python3 python3-pip

๐Ÿ“Œ Verify Installations

python3 --version
pip3 --version

๐Ÿ› ๏ธ Running Python Code

๐Ÿ“Œ Run Python Interactively (REPL)

python3

Example session:

>>> print("Hello from Python!")
Hello from Python!
>>> exit()

๐Ÿ“Œ Run a Python Script File

nano hello.py

Add this code:

print("Hello, WSL Ubuntu!")

Save with Ctrl+O, press Enter, and exit with Ctrl+X.
Then run it:

python3 hello.py

๐Ÿ“ฆ Installing Python Packages

๐Ÿ“Œ Use pip to Install Packages

pip3 install package-name

Example:

pip3 install requests

๐Ÿ“Œ Sample Script Using Requests

nano api_test.py

Add:

import requests
response = requests.get('https://httpbin.org/get')
print(response.json())

Run it:

python3 api_test.py

๐Ÿงช Practice Exercises

# Update and install Python
sudo apt update
sudo apt install python3 python3-pip

# Verify installation
python3 --version
pip3 --version

# Create and run a script
nano test.py
# Add: print("Testing Python in WSL")
python3 test.py

# Install a package and use it
pip3 install requests
nano api_test.py
# Add:
# import requests
# r = requests.get("https://httpbin.org/get")
# print(r.json())
python3 api_test.py

โœ… Summary

  • python3 โ€“ Launch Python interpreter
  • python3 filename.py โ€“ Run a Python script
  • pip3 install โ€“ Install Python packages
  • nano filename.py โ€“ Create/edit Python files
  • Python is versatile and easy to use in WSL Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *