- Как venv поменять версию питон
- How to use pyenv to manage Python versions
- How I actually use pyenv
- Selecting a Python version
- Using the selected Python version
- Используйте другую версию Python с virtualenv
- 19 ответов
- ======== VIRTUALENVWRAPPER =========
- Forums
- Create virtual environments with another Python version
- What is the difference between venv and virtualenv?
- Virtual environments with other Python version
Как venv поменять версию питон
This is a short article describing how you can change the Python interpreter version in an existing virtualenv. If you start working on a project and realize you wish you started with Python 2, or you started with version 2 and wish you started with version 3, this can easily be change.
In this article I use virtualenvwrapper for managing Python virtualenvs.
The first thing to consider is using two directory locations for your virtualenvs. One for your libraries and packages and a different location for your project files. This is the key for being able to disconnect and change your Python interpreter. Keeping your project files separate makes version control a little easier too.
Virtualenvwrapper comes with some convenient commands for managing your virtualenvs.
To change your Python version:
Deactivate your current environment session.
If you have many packages or libraries installed, it would be a good idea to make a requirements.txt file. Remember to edit version as necessary.
Remove the virtualenv with the wrapper command: rmvirtualenv
This will remove the virtualenv, but leave your project files.
Make a new virtualenv with the Python version you want.
Example: mkvirtualenv -p python3 env-name
You can specify the Python version with the -p flag and version. If you have a requirements.txt file, you can specify that with -r requirements.txt
Now bind your new virtualenv to your project directory. You can specify the full paths, but it is easier to have your new virtualenv activated and be in your project directory. Then, run the command:
How to use pyenv to manage Python versions
As a Python developer, I install new Python versions when they come out. We get new features and performance improvements, but we don’t always want to use the latest version for everything. Some projects use older Python versions, and other projects must use a specific Python version.
If you need to install multiple Python versions, going the ol’ installer route isn’t the best idea. You end up with multiple Python executables in your PATH , such as python , python2 , python3 , python3.7 , and so on. Also it becomes really tricky to distinguish minor versions, such as python3.10.3 from python3.10.4 .
So, pyenv to the rescue! This command-line tool will handle installing and running specific Python versions!
Their README file actually explains how it works and how to install it really well. Give it a read!
As a note, for Windows I’ve often use the pyenv-win project, which has worked well for me.
To install pyenv on MacOS, I’ve just gone for Homebrew:
After installing you’ll have to add a few things to your shell, to configure it. Detailed instructions are in the README.
How I actually use pyenv
The great thing about pyenv for me is that it just works, and I only use it at the very beginning of a project, to create a virtual environment.
Once I’ve created a virtual environment using a specific Python version (which I get from pyenv ), from then on I just activate the virtual environment to get that version, and I don’t have to faff around with pyenv any more.
First, see if the version of Python you want is available (you may have to update pyenv to see recent versions, which I do with brew update && brew upgrade pyenv ):
This will show you a long output, which may contain things like the following:
So now you know, you can install from these versions (and again, reminder to update to see the most recently-added versions).
To install a Python version:
Selecting a Python version
You can see the currently-selected Python version with this command:
And you can see all versions (including the currently selected one) with:
You can have a globally selected Python version, and then locally selected Python versions. The global version is used if no local version is selected.
You can select a local version with:
This creates a .python-version file in your current folder, which tells pyenv to use that Python version.
If you want to change the global Python version:
Using the selected Python version
Now, let’s create a virtual environment using pyenv :
This uses pyenv exec to run the python command, which will use Python 3.10.7 in our case. The -m venv .venv argument passed to python tells it to run the venv module, and gives it the name of .venv .
This will create a virtual environment in a folder called .venv .
And to be honest, this is how I use pyenv . That’s it, nothing more!
If you want to test your applications in multiple Python versions, you can also do so easily. Real Python has a great in-depth blog post that covers that, so feel free to check it out.
That’s everything! I hope you’ve found this interesting, and you’ve learned something new. If you want to delve deeper into Python and everything it has to offer, please consider joining our Complete Python Course. This mega-course covers many Python topics, and it’s currently on sale!
Используйте другую версию Python с virtualenv
У меня есть система Debian, в настоящее время работающая с python 2.5.4. Я получил virtualenv правильно установлен, все работает нормально. Есть ли вероятность, что я могу использовать virtualenv с другой версией Python?
Я скомпилировал Python 2.6.2 и хотел бы использовать его с некоторыми virtualenv. Достаточно ли перезаписать двоичный файл? Или мне нужно что-то изменить в отношении библиотек?
19 ответов
Просто используйте параметр —python (или короткий -p ) при создании экземпляра virtualenv, чтобы указать исполняемый файл Python, который вы хотите использовать, например:
NB Для Python 3.3 или более поздней версии см. Ответ Aelfinn ниже.
Это шаги, когда вы находитесь в среде общего хостинга, и вам нужно установить и выполнить Python из источника, а затем создать venv из вашей версии Python. Для Python 2.7.9 вы должны сделать что-то в этом направлении:
виртуальный env
Естественно, это может быть применимо к любой ситуации, когда вы хотите скопировать точную среду, в которой работаете и развертываете.
/.localpython/bin/virtualenv вместо просто virtualenv для завершения установки без ошибок. Кроме того, используйте source ve/bin/activate вместо source activate .
UPDATE: для Python3.6 приведенный ниже скрипт pyvenv устарел. Вместо этого в Документах Python предлагается создать виртуальную среду с помощью следующей команды:
Для python3 (3. 3+) используйте либо описанный выше метод, либо команду сценария pyvenv .
Обратите внимание, что venv не позволяет создавать virtualenv с другими версиями Python. Для этого установите и используйте пакет virtualenv .
Существует более простой способ,
Благодаря комментарию это работает только если у вас установлен python2.7 на уровне системы (например,/usr/bin/python2.7).
В противном случае, если вы используете доморощенный, вы можете использовать путь, чтобы дать вам то, что вы хотите.
Вы можете найти путь к вашей установке python с помощью
Это также будет работать с python 3.
В конечном итоге конденсация до:
В Windows для меня это работает:
без python.exe я получил WindowsError: [Error 5] Access is denied У меня есть Python2.7.1, установленный с virtualenv 1.6.1, и мне нужен python 2.5.2.
Mac OSX 10.6.8 (Snow Leopard):
1) Когда вы используете pip install virtualenv , команда pip связана с одной из ваших версий python, а virtualenv устанавливается в эту версию python. Ты можешь сделать
чтобы узнать, какая версия python. Если вы видите что-то вроде:
Вы можете увидеть версию python на выходе.
По умолчанию это будет версия python, которая используется для любой создаваемой вами новой среды. Однако вы можете указать любую версию python, установленную на вашем компьютере, для использования внутри новой среды с -p flag :
virtualenv my_env создаст папку в текущем каталоге, которая будет содержать исполняемые файлы Python, и копию команды [команда], которую вы можете использовать для установки других пакетов.
virtualenv просто копирует python из местоположения на вашем компьютере во вновь созданный каталог my_env/bin/.
2) Системный python находится в /usr/bin , в то время как различные версии python, которые я установил, по умолчанию были установлены в:
3) У различных питонов, которые я установил, есть имена, такие как python2.7 или python3.2 , и я могу использовать эти имена, а не полные пути.
======== VIRTUALENVWRAPPER =========
1) У меня возникли проблемы с тем, чтобы работать на виртуальном сервере. Вот что я вложил в
2) Параметр -p option работает по-разному с virtualenvwrapper: я должен указать полный путь к интерпретатору python, который будет использоваться в новой среде (когда я не хочу использовать стандартную версию python):
В отличие от virtualenv, virtualenvwrapper создаст среду в местоположении, указанном переменной окружения $ WORKON_HOME. Это держит все ваши среды в одном месте.
Forums
Dumb question, but is the best way to update my python version (3.4 —> 3.6) in a virtual environment to pip freeze the requirements, delete the old virtual environment folder, create a new one with the new python version, and install from the requirements.txt?
If so, is it possible to create a new virtualenv with the same name as the old one (hopefully that would allow me not to have to change anything else in my web app settings)?
yes, with one extra step- you will have to also change the webapp python version in the webapp tab. (also some packages might be supported in 3.4 but not in 3.6 etc, so you might have to debug and fix that)
I guess you could keep it the same name (but I believe the only thing you need to change is the virtualenv path in the webapps tab and then reload the webapp, so shouldn’t be a lot of changes even if you use a different name)
conrad | 4232 posts | PythonAnywhere staff | Aug. 3, 2017, 11:49 a.m. | permalink
I did the above (I needed to go from python 2.7 to 3.7) and I created the new env with the following from https://stackoverflow.com/questions/10218946/upgrade-python-in-a-virtualenv
Step 1: Freeze requirement & take a back-up of existing env
Step 2: Install Python 3.7 & activate virutal environment
Step 3: Install requirements
The problem at this point is that when I restart the webapp and reload my page, I get an error message saying that it can’t find django. (I then reinstalled django which of course killed everything so I restored my old env to get back to the starting point.)
Make sure that your web app is actually configured to use the virtualenv that you’re installing into and make sure that django is in your requirements file.
glenn | 9162 posts | PythonAnywhere staff | June 11, 2022, 10:47 a.m. | permalink
Create virtual environments with another Python version
Nothing more frustrating in a data science project than a library that doesn’t work in your particular Python version. Sometimes, you just need to install a virtual environment with another Python version.
First of all, if you are a venv user, I hate to break it to you. There’s no straightforward way to create a virtual environment with another Python version using venv. For this reason, you’ll have to install virtualenv.
What is the difference between venv and virtualenv?
- venv is a package that comes with Python 3. In other words: you don’t need to install an extra package to create virtual environments.
- On the other hand, virtualenv is library that you can download via pip install virtualenv.
Furthermore, according to the virtualenv documentation, venv is…
- is slower (by not having the app-data seed method),
- is not as extendable,
- cannot create virtual environments for arbitrarily installed python versions (and automatically discover these),
- is not upgrade-able via pip,
- does not have as rich programmatic API (describe virtual environments without creating them).
Virtual environments with other Python version
To create a virtual environment with another Python version, you have to take the following steps.
- Download the Python version that you need, e.g. Python 3.6
- Install the Python executable. I recommend a custom installation. There’s no need to add it to PATH.
- Run Virtual Studio Code (or any other editor or terminal). Windows: If the installation directory is within Program Files, run it as an Administrator.
- Install virtualenv in your main Python version via pip install virtualenv
- Create the virtual environment with virtualenv, and specify the -p parameter.
If your directory contains spaces, wrap it in double quotes. Like this:
py -m virtualenv -p="C:\Program Files\Python36\python.Exe" .virtenv