2023-03-12
Getting a Python 2 virtual environment (in 2023's twilight of Python 2)
Suppose, not entirely hypothetically, that you need to create a new
Python 2 virtual environment today; perhaps you need to install
some package to see how its old Python 2 version behaves. With
Python 3, creating a virtual environment is really easy; it's just
'python3 -m venv /tmp/pytest
'. With Python 2 today, you have two
complications. First, Python 2 doesn't have a venv
module (instead
it uses a 'virtualenv
' command), and second, your installed Python
2 environment may not have all of the necessary infrastructure
already set up since people are deprecating Python 2 and cutting
down any OS provided version of it to the bare minimum.
First, you need a Python 2 version of pip. Hopefully you have one
already; if not, you want the 2.7 version of get-pip.py
, but don't count on that URL
lasting forever, as the URL in my 2021 entry on this didn't. I haven't tested this latest version,
so cross your fingers. If you still care at all about Python 2, you
probably really want to make sure you have a pip2 at this point.
Once you have a pip2 in one way or another, you want to do a user
install of 'virtualenv
', with 'pip2 install --user virtualenv
'. This
will give you a ~/.local/bin/virtualenv command, which you may want to
rename to 'virtualenv2'. You can then use this to create your virtual
environment, 'virtualenv2 /tmp/pytest
'. The result should normally
have everything you need to use the virtualenv, including a pip2, and
you can then use this virtualenv pip2 to install the package or packages
you need to poke at.
Incidentally, if you just want to get a copy of the Python 2 version of
a particular package and not specifically install it somewhere, you can
just use pip2 to download it, with 'pip2 download <whatever>
'. I'm
not sure that the result is necessarily immediately usable and you'll
have to decode it yourself ('file
' may be your friend), but depending
on what you want this may be good enough.
(I took a quick look to see if there was an easier way to find out
the last supported Python 2 version of a package than 'pip2 download
<whatever>
', but as far as I can see there isn't.)
(This is one of the entries that I write for myself so that I have this information if I ever need it again, although I certainly hope not to.)
PS: Another option is to use the Python 2.7 version of PyPy, which I believe comes pre-set with its own pip2, although not its own already installed virtualenv. Depending on how concerned you are about differences in behavior between CPython 2.7 and PyPy 2.7, this might not be a good option.