Bootstrap FreeKB - Python (Scripting) - Install Python in a virtual environment on Linux
Python (Scripting) - Install Python in a virtual environment on Linux

Updated:   |  Python (Scripting) articles

Let's start by listing the current version of Python that is installed.

~]# python --version
Python 2.7.5

 

Many Linux systems have both version 2 and version 3 of Python installed, so let's also check for Python 3.

~]# python3 --version
Python 3.6.8

 

On a Red Hat distribution (CentOS, Fedora, Red Hat), ensure the following packages are installed as they are required for Python 3.9 and above.

dnf install gcc openssl-devel bzip2-devel libffi-devel zlib-devel

 

On a Debian distribution (Ubuntu, Mint), ensure the following packages are installed as they are required for Python 3.9 and above.

apt-get install gcc build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdm-dev libbz2-dev libc6-dev libsqlite3-dev tk-dev

 

Now let's say you want to create a Python virtual environment and then install a different version of Python in the virtual environment. Let's start by creating a directory for the version of Python we want to install in the virtual environment.

mkdir python3.9.6

 

Move into the newly created directory.

cd python3.9.6

 

Use wget to download the .tgz file for the version of Python you want to install.

wget https://www.python.org/ftp/python/3.9.6/Python-3.9.6.tgz

 

Extract the tar archive.

tar -zxpf Python-3.9.6.tgz

 

Move into the directory created after the tar was extracted.

cd Python-3.9.6

 

And then run the configure script with the --prefix option that points to the directory you created.

./configure --prefix=/path/to/python3.9.6

 

And then run the make command. You want this command to return Python build finished successfully!.

make

 

And then make altinstall.  It's important to use altinstall here and not "make install" so that the new Python install does not replace a current Python installation.

make altinstall

 

Now you are ready to create a Python virtual environment that uses the version of Python you just installed. 

Assuming you will be using version 3 of Python, the python3 -m venv <something unique> command can be used to create a virtual environment using the version of Python you just installed. 

python -m venv foo --python=/path/to/python3.9.6/bin/python

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 0e56b4 in the box below so that we can be sure you are a human.