Virtual Environment for My First Python Program
Creating and using a virtual environment is a best practice when working on Python projects. It helps isolate dependencies and avoids conflicts between different projects.
Why Use a Virtual Environment?
- To isolate packages used in different projects.
- To avoid conflicts between library versions.
- Essential when working with both Python 2 and Python 3.
- Helps prevent bugs and confusion caused by global installations.
- Makes your projects portable and reproducible.
Module Used: venv
Python provides the venv
module to create lightweight virtual
environments. It includes a standalone Python interpreter and pip.
Example: Create a Virtual Environment in ~/dev
1. Navigate to your project directory
cd ~/dev
2. Create the virtual environment
python -m venv python-dev
This will:
- Create a folder
python-dev
(if it doesn’t exist) - Copy the Python interpreter, standard library, and pip into it
Activate the Virtual Environment
On Windows:
Command Prompt (CMD):
python-dev\Scripts\activate.bat
PowerShell:
python-dev\Scripts\Activate.ps1
On Linux / macOS:
source python-dev/bin/activate
Once activated, your terminal prompt will change to show the environment name:
(python-dev) $
Writing Your First Python Program
1. Open VS Code in the environment directory:
cd python-dev
code main.py
2. Paste the following code in main.py
:
def main():
print("Hello, world!")
if __name__ == "__main__":
main()
else:
print("File invoked")
3. Run your script:
Make sure your virtual environment is activated, then run:
python main.py
Deactivating the Environment
To deactivate the virtual environment when you're done:
deactivate