Python – Using a virtual environment.

Introduction – Why use a virtual environment?

Using a virtual environment allows you to avoid installing Python modules globally which could break system tools or other projects.


Installation

If you are using Python 3.3 or newer the “venv” module is the preferred way to create and manage virtual environments.

You can check what version of Python you have via:

python --version

Enter fullscreen mode Exit fullscreen mode

If the version is older than 3.3 you can install the “virtualenv” module:

pip install virtualenv

Enter fullscreen mode Exit fullscreen mode


Creating the virtual environment

Creating the virtual environment is easy and can be done via:

# venv
python3 -m venv env

# virtualenv
virtualenv env

Enter fullscreen mode Exit fullscreen mode


Activating the virtual environment

Before you can start installing modules etc, you need to activate the environment. Activating the virtual environment will put the environment specific “python” and “pip” executables into your shell’s path.

source env/bin/activate

Enter fullscreen mode Exit fullscreen mode

You can check if the path has been updated via echoing it.

echo $PATH

Enter fullscreen mode Exit fullscreen mode

You should see the virtualenv directory being listed at the front.


Deactivating the virtual environment

Once you are done with the virtual environment you can simple deactivate it.

deactivate

Enter fullscreen mode Exit fullscreen mode

Simples.


Should you commit the virtual environment directory?

I personally wouldn’t recommend it.

I’d recommend putting the modules you need in a “requirements.txt” file, creating the virtual environment on the deployment server and then installing the modules needed via:

pip install -r requirements.txt

Enter fullscreen mode Exit fullscreen mode

Don’t forget to add the virtual environment directory to your “.gitignore” file.


Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee.

原文链接:Python – Using a virtual environment.

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容