How to create Python virtual environment, install packages and run scripts inside ?
- User
How to create Python virtual environment, install packages and run scripts inside ?
- Assistant
Creating a Python virtual environment allows you to manage dependencies and packages for different projects separately. Here's how to create a virtual environment, install packages, and run scripts inside it:
-
Install Virtual Environment Package (if not already installed): Generally, Python 3 comes with the
venvmodule to create virtual environments. If for some reason you don’t have this module, or you are using Python 2, you can installvirtualenvby running:pip install virtualenv -
Create a Virtual Environment: Navigate to your project directory in the terminal, then run the following command to create a new virtual environment. Replace
myenvwith your desired environment name.For Python 3:
python3 -m venv myenvor simply
pythoninstead ofpython3, depending on your system's configuration.For Python 2 (not recommended, as Python 2 is deprecated):
virtualenv myenv -
Activate the Virtual Environment: Before you can start using the virtual environment, you need to activate it.
On Linux or macOS:
source myenv/bin/activateOn Windows (cmd.exe):
myenv\Scripts\activateOn Windows (PowerShell):
.\myenv\Scripts\Activate.ps1You should see the name of your virtual environment prefixed on your terminal command line which indicates that it is currently active.
-
Install Required Packages: With the virtual environment activated, you can install packages using
pip. For example, to installrequestsyou would run:pip install requestsYou can also install multiple packages at once or use a
requirements.txtfile if you have one:pip install package1 package2 ...or:
pip install -r requirements.txt -
Run Scripts Inside the Virtual Environment: Any Python scripts you run while the virtual environment is active will use the environment’s settings and installed packages.
python my_script.py -
Deactivating the Virtual Environment: Once you are done with your work, you can deactivate the virtual environment to return to your global Python environment by running:
deactivate
Remember that each virtual environment is independent, and installing packages into one will not affect others. This is useful when different projects require different versions of the same package.
-