[python] Create a virtual environment

When your environment has conflicts related to versions of some library dependencies, the easiest and fastest way is to create a virtual environment and reconfigure the environment.
To create a new virtual environment in Python, you can follow these steps:

  1. Make sure the virtual environment tools are installed: First, make sure the venv or virtualenv tool is installed in the Python environment. In newer Python versions (such as Python 3.3 and above), venv is a built-in module and does not require additional installation. If you are using an older Python version, consider installing and using virtualenv.

    • Install virtualenv:
      pip install virtualenv
  2. Create a virtual environment: Open a terminal or command prompt and enter the directory where you want to create a virtual environment. Then execute the following command to create a virtual environment named myenv:

    • Use venv:
      python -m venv envname
    • Using virtualenv:
      virtualenv envname
  3. Activate the virtual environment: Depending on the operating system used, execute the following command to activate the virtual environment:

    • On Windows (using venv):activate envname
    • On Windows (using virtualenv):\myenv\Scripts\activate.bat
    • On macOS and Linux (using venv or virtualenv):source myenv/bin/activate

After activating a virtual environment, you will see the environment name (for example (myenv)) in front of the prompt in the terminal or command prompt. This means you have successfully entered the virtual environment.

4. Exit the virtual environment: deactivate. Will return the python global environment

By creating virtual environments, you can create independent, isolated Python environments for each project or task without interfering with other projects or the global environment. This is useful for managing package dependencies and ensuring environmental consistency for your project.

Guess you like

Origin blog.csdn.net/m0_51662391/article/details/131599881