Как удалить pyenv ubuntu
Python стал довольно популярным языком программирования из-за простоты использования по сравнению с другими языками. Следовательно на этом языке написано множество приложений и инструментов для Linux.
Многие из них не обновлены до новых версий Python. из-за увольнения программиста или по какой-либо другой причине, но приложение все еще работает или для него требуется определенная версия Python.
Это может привести к большой проблемеВот почему мы можем использовать отличный инструмент, который позволит нам устанавливать различные версии этого языка в нашей системе.
На Pyenv
Инструмент, о котором мы поговорим сегодня, - это Pyenv. это простой, мощный, бесплатный кроссплатформенный инструмент с открытым исходным кодом, который сосредоточился на управлении несколькими версиями Python в системах Linux.
Pyenv - это инструмент, основанный на rbenv и ruby-build и что он был изменен, чтобы он мог работать с языком программирования Python, что вкратце заключается в том, что это вилка для Python.
Этот отличный инструмент помогает нам устанавливать, управлять и переключаться между несколькими версиями Python, что обычно делается для тестирования кода в нескольких средах Python.
Этот инструмент может быть очень полезен программистам Вы хотите протестировать свои творения, написанные на Python, в нескольких средах и в разных версиях Python.
С его помощью вы избавитесь от необходимости устанавливать и удалять каждую версию Python в своих системах или переходить с одного компьютера на другой с одной и той же системой, но с другой версией языка программирования.
Между sосновные характеристики этого инструмента мы можем выделить:
- Уметь изменять глобальную версию Python для каждого пользователя.
- Установка локальной версии Python для каждого проекта.
- Управление виртуальными средами, созданными anaconda или virtualenv.
- Позволяет вам переопределить версию Python с помощью переменной среды.
- Ищите команды из нескольких версий Python и не только.
Как установить Pyenv на Ubuntu 18.04 и производные?
Si хочу установить этот отличный инструмент, мы должны открыть терминал с помощью Ctrl + Alt + T и мы собираемся установить некоторые зависимости для приложения:
Сейчас мы можем приступить к установке Pyenv на наши компьютеры Это можно сделать, загрузив инструмент из вашего пространства на github, и мы будем использовать скрипт pyenv-установщик.
Все, что тебе нужно сделать, это выполните следующую команду в своем терминале, чтобы установить pyenv.
Выполняя это, мы должны дождаться его загрузки и установки. В конце установки установщик уведомит вас о необходимости добавления Pyenv в вашу личную папку.
Для чего должен добавить следующие строки в ваш файл
/ .bash_profile, мы должны открыть терминал и выполнить:
И мы добавляем следующие строки в конец файла, здесь мы должны заменить «USER» на ваше системное имя пользователя.
Мы сохраняем изменения с помощью Ctrl + O и выходим из nano с помощью Ctrl + X, теперь мы должны сделать эти изменения действительными, выполнив следующую команду:
Pyenv готов к использованию.
Как использовать pyenv в Ubuntu?
После завершения установки мы можем убедиться, что он запущен, и узнать, какие версии Python доступны для использования в нашей системе.
Для этого мы собираемся открыть терминал, и мы собираемся выполнить:
O они также могут запускать:
Эта команда отобразит все доступные версии.
Сейчас чтобы узнать тот, который мы установили, мы должны выполнить:
к установить любую из доступных версий что Pyenv показал нам шаги назад, мы можем выполнить эту команду:
Где мы заменяем x на версию Python, которую хотим установить в системе.
Наконец, чтобы изменить версию Python, мы делаем это с помощью:
Если вы хотите узнать больше об этом инструменте, вы можете проконсультироваться по следующей ссылке.
Содержание статьи соответствует нашим принципам редакционная этика. Чтобы сообщить об ошибке, нажмите здесь.
Полный путь к статье: Убунлог » ПО » Pyenv: установите несколько версий Python в вашей системе
Simple Python Version Management: pyenv
pyenv lets you easily switch between multiple versions of Python. It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.
This project was forked from rbenv and ruby-build, and modified for Python.
- Lets you change the global Python version on a per-user basis.
- Provides support for per-project Python versions.
- Allows you to override the Python version with an environment variable.
- Searches for commands from multiple versions of Python at a time. This may be helpful to test across Python versions with tox.
In contrast with pythonbrew and pythonz, pyenv does not.
- Depend on Python itself. pyenv was made from pure shell scripts. There is no bootstrap problem of Python.
- Need to be loaded into your shell. Instead, pyenv's shim approach works by adding a directory to your $PATH .
- Manage virtualenv. Of course, you can create virtualenv yourself, or pyenv-virtualenv to automate the process.
Table of Contents
At a high level, pyenv intercepts Python commands using shim executables injected into your PATH , determines which Python version has been specified by your application, and passes your commands along to the correct Python installation.
When you run a command like python or pip , your operating system searches through a list of directories to find an executable file with that name. This list of directories lives in an environment variable called PATH , with each directory in the list separated by a colon:
Directories in PATH are searched from left to right, so a matching executable in a directory at the beginning of the list takes precedence over another one at the end. In this example, the /usr/local/bin directory will be searched first, then /usr/bin , then /bin .
pyenv works by inserting a directory of shims at the front of your PATH :
Through a process called rehashing, pyenv maintains shims in that directory to match every Python command across every installed version of Python— python , pip , and so on.
Shims are lightweight executables that simply pass your command along to pyenv. So with pyenv installed, when you run, say, pip , your operating system will do the following:
- Search your PATH for an executable file named pip
- Find the pyenv shim named pip at the beginning of your PATH
- Run the shim named pip , which in turn passes the command along to pyenv
Choosing the Python Version
When you execute a shim, pyenv determines which Python version to use by reading it from the following sources, in this order:
The PYENV_VERSION environment variable (if specified). You can use the pyenv shell command to set this environment variable in your current shell session.
The application-specific .python-version file in the current directory (if present). You can modify the current directory's .python-version file with the pyenv local command.
The first .python-version file found (if any) by searching each parent directory, until reaching the root of your filesystem.
The global $(pyenv root)/version file. You can modify this file using the pyenv global command. If the global version file is not present, pyenv assumes you want to use the "system" Python. (In other words, whatever version would run if pyenv weren't in your PATH .)
Locating the Python Installation
Once pyenv has determined which version of Python your application has specified, it passes the command along to the corresponding Python installation.
Each Python version is installed into its own directory under $(pyenv root)/versions .
For example, you might have these versions installed:
- $(pyenv root)/versions/2.7.8/
- $(pyenv root)/versions/3.4.2/
- $(pyenv root)/versions/pypy-2.4.0/
As far as Pyenv is concerned, version names are simply directories under $(pyenv root)/versions .
Managing Virtual Environments
There is a pyenv plugin named pyenv-virtualenv which comes with various features to help pyenv users to manage virtual environments created by virtualenv or Anaconda. Because the activate script of those virtual environments are relying on mutating $PATH variable of user's interactive shell, it will intercept pyenv's shim style command execution hooks. We'd recommend to install pyenv-virtualenv as well if you have some plan to play with those virtual environments.
Homebrew in macOS
Consider installing with Homebrew:
OPTIONAL. To fix brew doctor 's warning ""config" scripts exist outside your system or Homebrew directories"
If you're going to build Homebrew formulae from source that link against libpython like Tkinter or NumPy (This is only generally the case if you are a developer of such a formula, or if you have an EOL version of MacOS for which prebuilt bottles are no longer available and are using such a formula).
To avoid them accidentally linking against a Pyenv-provided Python, add the following line into your interactive shell's configuration:
Pyenv does not officially support Windows and does not work in Windows outside the Windows Subsystem for Linux. Moreover, even there, the Pythons it installs are not native Windows versions but rather Linux versions run through a compatibility layer -- so you won't get Windows-specific functionality.
If you're in Windows, we recommend using @kirankotari's pyenv-win fork -- which does install native Windows Python versions.
Basic GitHub Checkout
This will get you going with the latest version of Pyenv and make it easy to fork and contribute any changes back upstream.
Check out Pyenv where you want it installed. A good place to choose is $HOME/.pyenv (but you can install it somewhere else):
Optionally, try to compile a dynamic Bash extension to speed up Pyenv. Don't worry if it fails; Pyenv will still work normally:
Configure your shell's environment for Pyenv
Note: The below instructions for specific shells are designed for common shell setups; they also install shell functions into interactive shells only.
If you have an uncommon setup and/or needs and they don't work for you, use the Advanced Configuration section below to figure out what you need to do in your specific case.
General MacOS note: Make sure that your terminal app is configured to run the shell as a login shell (especially if you're using an alternative terminal app and/or shell). The configuration samples for MacOS are written under this assumption and won't work otherwise.
For Bash:
/.bashrc (Debian, Ubuntu, Mint):
/.bashrc (Red Hat, Fedora, CentOS):
If you have no
/.bash_profile and your /etc/profile sources
Otherwise if you have no stock
In MacOS, make sure that your terminal app runs the shell as a login shell.
Temporary environments (CI, Docker, batch jobs):
In CI/build environments, paths and the environment are usually already set up for you in one of the above ways. You may only need to install Pyenv as a shell function into the (noninteractive) shell that runs the batch script, and only if you need subcommands that require pyenv to be a shell function (e.g. shell and Pyenv-Virtualenv's activate ).
If you are installing Pyenv yourself as part of the batch job, after installing the files, run the following in the job's shell to be able to use it.
For Zsh:
MacOS, if Pyenv is installed with Homebrew:
Make sure that your terminal app runs the shell as a login shell.
MacOS, if Pyenv is installed with a Git checkout:
Make sure that your terminal app runs the shell as a login shell.
Other OSes:
For Fish shell:
Execute this interactively:
And add this to
If Fish is not your login shell, also follow the Bash/Zsh instructions to add to
Restart your login session for the changes to profile files to take effect. E.g. if you're in a GUI session, you need to fully log out and log back in.
In MacOS, restarting terminal windows is enough (because MacOS runs shells in them as login shells by default).
Install Python build dependencies before attempting to install a new Python version.
Install Python versions into $(pyenv root)/versions . For example, to download and install Python 2.7.8, run:
NOTE: If you need to pass a configure option to a build, please use the CONFIGURE_OPTS environment variable.
NOTE: If you are having trouble installing a Python version, please visit the wiki page about Common Build Problems.
If you've installed Pyenv using Homebrew, upgrade using:
If you've installed Pyenv using the instructions above, you can upgrade your installation at any time using Git.
To upgrade to the latest development version of pyenv, use git pull :
To upgrade to a specific release of Pyenv, check out the corresponding tag:
The simplicity of pyenv makes it easy to temporarily disable it, or uninstall from the system.
To disable Pyenv managing your Python versions, simply remove the pyenv init invocations from your shell startup configuration. This will remove Pyenv shims directory from PATH , and future invocations like python will execute the system Python version, as it was before Pyenv.
pyenv will still be accessible on the command line, but your Python apps won't be affected by version switching.
To completely uninstall Pyenv, remove all configuration lines for it from your shell startup configuration, and then remove its root directory. This will delete all Python versions that were installed under $(pyenv root)/versions/ directory:
If you've installed Pyenv using a package manager, as a final step, perform the Pyenv package removal. For instance, for Homebrew:
Skip this section unless you must know what every line in your shell profile is doing.
pyenv init is the only command that crosses the line of loading extra commands into your shell. Coming from RVM, some of you might be opposed to this idea.
Also see the Environment variables section for the environment variables that control Pyenv's behavior.
eval "$(pyenv init --path)" :
- Sets up your shims path. This is the only requirement for pyenv to function properly. You can do this by hand by prepending $(pyenv root)/shims to your $PATH .
eval "$(pyenv init --path)" is supposed to be run in your session's login shell startup script -- so that all processes in the session get access to Pyenv's functionality and it only runs once, avoiding breaking PATH in nested shells (e.g. shells started from editors/IDEs).
In Linux, GUI managers typically act as a sh login shell, running /etc/profile and
/.profile at their startup. MacOS' GUI doesn't do that, so its terminal emulator apps run their shells as login shells by default to compensate.
eval "$(pyenv init -)" :
Installs autocompletion. This is entirely optional but pretty useful. Sourcing $(pyenv root)/completions/pyenv.bash will set that up. There is also a $(pyenv root)/completions/pyenv.zsh for Zsh users.
Rehashes shims. From time to time you'll need to rebuild your shim files. Doing this on init makes sure everything is up to date. You can always run pyenv rehash manually.
Installs pyenv into the current shell as a shell function. This bit is also optional, but allows pyenv and plugins to change variables in your current shell, making commands like pyenv shell possible. The sh dispatcher doesn't do anything crazy like override cd or hack your shell prompt, but if for some reason you need pyenv to be a real script rather than a shell function, you can safely skip it.
eval "$(pyenv init -)" is supposed to run at any interactive shell's startup (including nested shells) so that you get completion and convenience shell functions.
To see exactly what happens under the hood for yourself, run pyenv init - or pyenv init --path .
If you don't want to use pyenv init and shims, you can still benefit from pyenv's ability to install Python versions for you. Just run pyenv install and you will find versions installed in $(pyenv root)/versions , which you can manually execute or symlink as required.
Uninstalling Python Versions
As time goes on, you will accumulate Python versions in your $(pyenv root)/versions directory.
To remove old Python versions, pyenv uninstall command to automate the removal process.
Alternatively, simply rm -rf the directory of the version you want to remove. You can find the directory of a particular Python version with the pyenv prefix command, e.g. pyenv prefix 2.6.8 .
You can affect how pyenv operates with the following settings:
The pyenv source code is hosted on GitHub. It's clean, modular, and easy to understand, even if you're not a shell hacker.
Tests are executed using Bats:
Please feel free to submit pull requests and file bugs on the issue tracker.
Note that the environment is not active. I'm running Ubuntu 11.10. Any ideas? I've tried rebooting my system to no avail.
17 Answers 17
"The only way I can remove it seems to be: sudo rm -rf venv "
That's it! There is no command for deleting your virtual environment. Simply deactivate it and rid your application of its artifacts by recursively removing it.
Note that this is the same regardless of what kind of virtual environment you are using. virtualenv , venv , Anaconda environment, pyenv , pipenv are all based the same principle here.
Just to echo what @skytreader had previously commented, rmvirtualenv is a command provided by virtualenvwrapper , not virtualenv . Maybe you didn't have virtualenvwrapper installed?
8,617 6 6 gold badges 57 57 silver badges 56 56 bronze badgesRemove an environment, in the $WORKON_HOME .
You must use deactivate before removing the current environment.
3,246 1 1 gold badge 20 20 silver badges 34 34 bronze badgesYou can remove all the dependencies by recursively uninstalling all of them and then delete the venv.
Edit including Isaac Turner commentary
Simply remove the virtual environment from the system.There's no special command for it
If you are using pyenv, it is possible to delete your virtual environment:
Removing a virtual environment is simply done by deactivating it and deleting the environment folder with all its contents:
1. Remove the Python environment
There is no command to remove a virtualenv so you need to do that by hand, you will need to deactivate if you have it on and remove the folder:
2. Create an env. with another Python version
When you create an environment the python uses the current version by default, so if you want another one you will need to specify at the moment you are creating it. To make and env. with Python 3.X called MyEnv just type:
Now to make with Python 2.X use virtualenv instead of venv :
3. List all Python versions on my machine
If any of the previous lines of code didn't worked you probably don't have the specific version installed. First list all your versions with:
Установка pyenv в Unix/Linux
Установка pyenv в CentOS/Fedora/RedHat
Подключаем EPEL репозиторий:
Далее, стоит установить следующие пакеты:
Имеется простой скрипт для установки данного ПО, можно использовать:
После установки, стоит настроить и потом, можно будет юзать данную тулу.
Установка pyenv в Debian/Ubuntu
Стоит установить следующие пакеты:
Имеется простой скрипт для установки данного ПО, можно использовать:
После установки, стоит настроить и потом, можно будет юзать данную тулу.
Установка pyenv в MacOS
Ставим homebrew, статью можно взять тут:
Выполним поиск пакета:
Чтобы поставить данное ПО, выполняем:
Перейдем к настройке.
Настройка pyenv в Unix/Linux
Просто добавьте этот код в конец вашего
/ .bashrc и затем загрузите ваш профиль, чтобы загрузить эти дополнения:
Можно уже юзать!
Использование pyenv в Unix/Linux
Для того, чтобы посмотреть какие версии python используется на данный момент, имеется команда:
Для установки какой-либо версии, используем:
Смотрим что имеется в системе:
Чтобы переключится на нужную версию, используем:
Так же, можно будет использовать:
Я пока что буду использовать:
Для глобального использования, можно выставить тоже нужную(ые) версию(и):
Можно выставить конкретную версию питона для shell оболочки, например:
Как это выглядит на картинке:
Сейчас, я выставлю нужные мне версии:
Смотрим версию питона:
Смотрим где находится питон:
Для получения списка команд, множно использовать:
Получить помощь можно так:
Или, для какой-то конкретной команды:
Т.е для активации созданной среды, используем:
Для диактивации, следующая команда:
Для удаления версии питона с ОС, используем:
Для обновления pyenv, имеется конманда:
Для удаления, используйте:
Так же, стоит удалить следующие строки с
One thought on “ Установка pyenv в Unix/Linux ”
Устанавливаешь такой это все, потом пишешь pipenv shell и наблюдаешь как он создает окружение из версии пайтон в /usr/bin/python3 и пофигу ему что ты поставил самую последнею версию, и ты печальный идешь и компилишь ее по нормальному
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.
Pyenv is a fantastic tool for installing and managing multiple Python versions. It enables a developer to quickly gain access to newer versions of Python and keeps the system clean and free of unnecessary package bloat. It also offers the ability to quickly switch from one version of Python to another, as well as specify the version of Python a given project uses and can automatically switch to that version. This tutorial covers how to install pyenv on Ubuntu 18.04.
Preflight Check:
- This tutorial was performed as the root user on a Liquid Web Self-Managed VPS Ubuntu 18.04 server.
It’s always a good idea to start off any installation process by updating system packages:
Once that has finished up, run the following command to install all of pyenv’s dependencies:
To install the latest version of pyenv and provide a straightforward method for updating it, run the following command to pull it down from GitHub:
Next, to properly configure pyenv for use on the system, run the following block of commands to set some important environment variables and setup pyenv autocompletion:
Finally, to start using pyenv, restart the shell by running:
To verify that pyenv is installed correctly, we will try installing a new version of Python. First, we will list the available versions of Python:
The list of the available version is long. Let’s go ahead and install Python version 3.8.3:
Do not be surprised if it takes a while for this command to run. Pyenv is building this version of Python from source.
To verify that Python 3.8.3 is now installed run the pyenv versions command:
Now for further verification, change the version of Python to 3.8.3 and drop into a python shell .
Switching back is just as easy!
Useful Commands
Finally, to get an idea of all the commands and features pyenv has to offer, run the following command:
Some useful pyenv commands are as follows.
The full documentation for pyenv can be found at GitHub .
There you have it! With pyenv installed, you’re off and running with more granular control of your Python environment!
Our Support Teams are filled with talented Linux technicians and System administrators who have an intimate working knowledge of multiple web hosting technologies, especially those discussed in this article.
If you are a Fully Managed VPS server, Cloud Dedicated, VMWare Private Cloud, Private Parent server or a Dedicated server owner and you are uncomfortable with performing any of the steps outlined above, we can be reached via phone @800.580.4985, a chat or support ticket to assist you.
Читайте также: