- Virtualenv
- Installation
- Usage
- Virtualenvwrapper
- Marina Mele’s site
- Learn about Python, Django, Marketing and Science
- Install Python 3 on Mac OS X and use virtualenv and virtualenvwrapper
- Install Xcode and Homebrew
- Install Python 3
- Create Virtual environments with pyvenv
- Установка и настройка Pуthon, Django и virtualenv на Mac OS
- Основные шаги:
- Установка Homebrew
- Установка Python3
- Установка virtualenv
- Создание изолированного окружения для проекта
- Запуск изолированного окружения
- Установка Django
- Создание проекта
- Запуск проекта
- venv — Creation of virtual environments¶
- Creating virtual environments¶
- An example of extending EnvBuilder В¶
Virtualenv
Virtualenv is a tool that lets you create an isolated Python environment for your project. It creates an environment that has its own installation directories, that doesn’t share dependencies with other virtualenv environments (and optionally doesn’t access the globally installed dependencies either). You can even configure what version of Python you want to use for each individual environment. It’s very much recommended to use virtualenv when dealing with Python applications.
Installation
To install virtualenv run:
Usage
If you have a project in a directory called my-project you can set up virtualenv for that project by running:
If you want your virtualenv to also inherit globally installed packages run:
These commands create a venv/ directory in your project where all dependencies are installed. You need to activate it first though (in every terminal instance where you are working on your project):
You should see a (venv) appear at the beginning of your terminal prompt indicating that you are working inside the virtualenv . Now when you install something like this:
It will get installed in the venv/ folder, and not conflict with other projects.
To leave the virtual environment run:
Important: Remember to add venv to your project’s .gitignore file so you don’t include all of that in your source code.
It is preferable to install big packages (like Numpy), or packages you always use (like IPython) globally. All the rest can be installed in a virtualenv .
Virtualenvwrapper
To make it easier to work on multiple projects that has separate environments you can install virtualenvwrapper . It’s an extension to virtualenv and makes it easier to create and delete virtual environments without creating dependency conflicts.
To install virtualenvwrapper run:
Depending on your setup you might need to install it using sudo . Read the installation documentation for more information.
Note: virtualenvwrapper keeps all the virtual environments in
/.virtualenv while virtualenv keeps them in the project directory.
Источник
Marina Mele’s site
Learn about Python, Django, Marketing and Science
Install Python 3 on Mac OS X and use virtualenv and virtualenvwrapper
This post explains how to install Python 3 in a Mac OS X, both Mavericks and Yosemite. Check this post if you want to clean install Python 2.7. You can also install both! 🙂
It also shows how to use virtualenv and virtualenvwrapper with Python 3. Don’t miss it!
Like with Python 2.7, we need to install first Xcode and Homebrew.
Install Xcode and Homebrew
First of all, install Xcode if you don’t have it already. You can find it in the Apple Store.
Next, we need to install the Command Line Tools of Xcode. Open a Terminal and type:
this should trigger a pop-up window that will ask you to install the Command Line Tools. If you have some trouble installing these tools, you might find useful this post on Stackoverflow.
Next, we need to install Homebrew. In the Terminal, type this command line:
Now, we need to insert the Homebrew directory at the top of the PATH environment variable. In this way, some Homebrew installations will take precedence over stock OS X binaries. Open or create the file
/.bash_profile and write:
Close your Terminal and open it again to make these changes effective.
Install Python 3
you will see the available python-related packages to install, and python3 should be among them. Let’s install it!
You can check which version is installed by typing
And you can open it with:
Moreover, when you install python with Homebrew, you also install:
- the corresponding pip package manager, which is called pip3
- the corresponding Setuptools
- pyvenv, and alternative to virtualenv — cool!!
Create Virtual environments with pyvenv
Now that you have Python3 you also have pyvenv, a tool to create virtual environments (similar to virtualenv). However, there is one important remark about the version of pyvenv you have installed: only if you installed Python 3.4 or latter, pyvenv will also install pip when creating a new virtual environment.
Let’s create a new virtual envirnoment, named myenv, using pyvenv:
Источник
Установка и настройка Pуthon, Django и virtualenv на Mac OS
Apr 22, 2020 · 3 min read
Я начал изучать возможности Django. Но раньше я работал только с DLE CMS и WordPress. Поэтому решил почитать инструкции по установке и настройке Джанго, с учетом того, что у меня Mac OS.
Стоит немного остановиться на том, что такое Django. Это достаточно мощный и уважаемый среди разработчиков фреймворк для создания сайтов, написанный на Python. Django считается очен быстрым и безопасным фреймворком, а благодаря своей модульности он очень гибкий и хорошо масштабируется.
Есть очень много р азных туториалов по установке, настройке и запуску Django. Но часть из них или достаточно объемные, или упускают какие-то важные вещи. В этой статье я постараюсь описать основные шаги, необходимые для запуска проекта на Python-Django под Mac OS.
Основные шаги:
- Установка Homebrew.
- Установка Python 3.
- Установка virtualenv.
- Создание изолированного окружения для проекта.
- Запуск изолированного окружения.
- Установка Django.
- Создание проекта.
- Запуск проекта!
Установка Homebrew
Homebrew — бесплатная открытая система управления программными проектами, которая упрощает установку программного обеспечения на операционную систему Mac OS. Homebrew использует Github для расширения поддержки пакетов, за счет вклада пользователей.
Если у вас не установлен Hombrew, необходимо запустить в терминале команду:
Установка Python3
Изначально Mac OS имеет предустановленный python версии 2. Поэтому, послу установки 3 версии питона, для доступа именно к python3 необходимо запускать его из терминала с командой python3.
Чтобы проверить версию python, надо запустить в терминале команду
Вы должны получить сообщение с версией установленного python.
Установка virtualenv
virtualenv — инструмент для создания изолированного виртуального окружения Python. Благодаря этому инструменту можно создать несколько разных проектов python, с разным набором библиотек на одном устройстве. Например, если вы захотите использовать разные версии одного и того же модуля в разных проектах.
После установки virtualenv мы установим все другие пакеты, в том числе и django в изолированные окружения.
Создание изолированного окружения для проекта
Создаем папку, в которой будет храниться проект. Пример команды в терминале.
И переходим в нее:
Создаем виртуальное окружение для проекта:
Где “ptest” — это название изолированного окружения, на ваше усмотрение.
Запуск изолированного окружения
После создания окружения, необходимо его активировать, чтобы установить все необходимые модули. Для этого запускаем в терминале команду:
Чтобы определить, в каком окружении вы находитесь, посмотрите на префикс в терминале, в круглых скобках будет указано название.
Так как изолированное окружение создавалось при помощи python3, в этом окружении можно запускать команды сразу через python, а не python3, так же как и pip, вместо pip3.
Чтобы завершить работу изолированного окружения, достаточно написать команду
Установка Django
Снова запустим изолированное окружение и через pip установим django.
Где “2.2” — необходимая версия джанго.
Создание проекта
Все готово для создания проекта. Достаточно написать в терминале (с запущенной виртуальной средой):
Поздравляю, вы создали свой первый проект на Django. Структура папок будет такой:
- project_test —домашняя папка проекта
- project1 — папка проекта django
- project1 — корневая папка
- ptest — виртуальная среда проекта
Запуск проекта
В Django встроен простой виртуальный веб-сервер. Не надо устанавливать никаких других программ на локальной машине. Чтобы его проверить, запустите в терминале команду:
Осталось проверить что сервер запущен, для этого в браузере открываем адрес http://127.0.0.1:8000.
Поздравляю, вы запустили свой первый проект на Django!
Источник
venv — Creation of virtual environments¶
New in version 3.3.
Source code: Lib/venv/
The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.
See PEP 405 for more information about Python virtual environments.
Creating virtual environments¶
Creation of virtual environments is done by executing the command venv :
Running this command creates the target directory (creating any parent directories that don’t exist already) and places a pyvenv.cfg file in it with a home key pointing to the Python installation from which the command was run (a common name for the target directory is .venv ). It also creates a bin (or Scripts on Windows) subdirectory containing a copy/symlink of the Python binary/binaries (as appropriate for the platform or arguments used at environment creation time). It also creates an (initially empty) lib/pythonX.Y/site-packages subdirectory (on Windows, this is Lib\site-packages ). If an existing directory is specified, it will be re-used.
Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.
Changed in version 3.5: The use of venv is now recommended for creating virtual environments.
On Windows, invoke the venv command as follows:
Alternatively, if you configured the PATH and PATHEXT variables for your Python installation :
The command, if run with -h , will show the available options:
Changed in version 3.9: Add —upgrade-deps option to upgrade pip + setuptools to the latest on PyPI
Changed in version 3.4: Installs pip by default, added the —without-pip and —copies options
Changed in version 3.4: In earlier versions, if the target directory already existed, an error was raised, unless the —clear or —upgrade option was provided.
While symlinks are supported on Windows, they are not recommended. Of particular note is that double-clicking python.exe in File Explorer will resolve the symlink eagerly and ignore the virtual environment.
On Microsoft Windows, it may be required to enable the Activate.ps1 script by setting the execution policy for the user. You can do this by issuing the following PowerShell command:
PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
The created pyvenv.cfg file also includes the include-system-site-packages key, set to true if venv is run with the —system-site-packages option, false otherwise.
Unless the —without-pip option is given, ensurepip will be invoked to bootstrap pip into the virtual environment.
Multiple paths can be given to venv , in which case an identical virtual environment will be created, according to the given options, at each provided path.
Once a virtual environment has been created, it can be “activated” using a script in the virtual environment’s binary directory. The invocation of the script is platform-specific ( must be replaced by the path of the directory containing the virtual environment):
Command to activate virtual environment
PS C:\> \Scripts\Activate.ps1
When a virtual environment is active, the VIRTUAL_ENV environment variable is set to the path of the virtual environment. This can be used to check if one is running inside a virtual environment.
You don’t specifically need to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically.
You can deactivate a virtual environment by typing “deactivate” in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically a script or shell function will be used).
New in version 3.4: fish and csh activation scripts.
New in version 3.8: PowerShell activation scripts installed under POSIX for PowerShell Core support.
A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python, i.e., one which is installed as part of your operating system.
A virtual environment is a directory tree which contains Python executable files and other files which indicate that it is a virtual environment.
Common installation tools such as setuptools and pip work as expected with virtual environments. In other words, when a virtual environment is active, they install Python packages into the virtual environment without needing to be told to do so explicitly.
When a virtual environment is active (i.e., the virtual environment’s Python interpreter is running), the attributes sys.prefix and sys.exec_prefix point to the base directory of the virtual environment, whereas sys.base_prefix and sys.base_exec_prefix point to the non-virtual environment Python installation which was used to create the virtual environment. If a virtual environment is not active, then sys.prefix is the same as sys.base_prefix and sys.exec_prefix is the same as sys.base_exec_prefix (they all point to a non-virtual environment Python installation).
When a virtual environment is active, any options that change the installation path will be ignored from all distutils configuration files to prevent projects being inadvertently installed outside of the virtual environment.
When working in a command shell, users can make a virtual environment active by running an activate script in the virtual environment’s executables directory (the precise filename and command to use the file is shell-dependent), which prepends the virtual environment’s directory for executables to the PATH environment variable for the running shell. There should be no need in other circumstances to activate a virtual environment; scripts installed into virtual environments have a “shebang” line which points to the virtual environment’s Python interpreter. This means that the script will run with that interpreter regardless of the value of PATH . On Windows, “shebang” line processing is supported if you have the Python Launcher for Windows installed (this was added to Python in 3.3 — see PEP 397 for more details). Thus, double-clicking an installed script in a Windows Explorer window should run the script with the correct interpreter without there needing to be any reference to its virtual environment in PATH .
The high-level method described above makes use of a simple API which provides mechanisms for third-party virtual environment creators to customize environment creation according to their needs, the EnvBuilder class.
class venv. EnvBuilder ( system_site_packages = False , clear = False , symlinks = False , upgrade = False , with_pip = False , prompt = None , upgrade_deps = False ) В¶
The EnvBuilder class accepts the following keyword arguments on instantiation:
system_site_packages – a Boolean value indicating that the system Python site-packages should be available to the environment (defaults to False ).
clear – a Boolean value which, if true, will delete the contents of any existing target directory, before creating the environment.
symlinks – a Boolean value indicating whether to attempt to symlink the Python binary rather than copying.
upgrade – a Boolean value which, if true, will upgrade an existing environment with the running Python — for use when that Python has been upgraded in-place (defaults to False ).
with_pip – a Boolean value which, if true, ensures pip is installed in the virtual environment. This uses ensurepip with the —default-pip option.
prompt – a String to be used after virtual environment is activated (defaults to None which means directory name of the environment would be used). If the special string «.» is provided, the basename of the current directory is used as the prompt.
upgrade_deps – Update the base venv modules to the latest on PyPI
Changed in version 3.4: Added the with_pip parameter
New in version 3.6: Added the prompt parameter
New in version 3.9: Added the upgrade_deps parameter
Creators of third-party virtual environment tools will be free to use the provided EnvBuilder class as a base class.
The returned env-builder is an object which has a method, create :
Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception.
The create method of the EnvBuilder class illustrates the hooks available for subclass customization:
Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory.
Creates the pyvenv.cfg configuration file in the environment.
Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.
Installs activation scripts appropriate to the platform into the virtual environment.
Upgrades the core venv dependency packages (currently pip and setuptools ) in the environment. This is done by shelling out to the pip executable in the environment.
New in version 3.9.
A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.
Changed in version 3.7.2: Windows now uses redirector scripts for python[w].exe instead of copying the actual binaries. In 3.7.2 only setup_python() does nothing unless running from a build in the source tree.
Changed in version 3.7.3: Windows copies the redirector scripts as part of setup_python() instead of setup_scripts() . This was not the case in 3.7.2. When using symlinks, the original executables will be linked.
In addition, EnvBuilder provides this utility method that can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment.
install_scripts ( context , path ) В¶
path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
__VENV_DIR__ is replaced with the absolute path of the environment directory.
__VENV_NAME__ is replaced with the environment name (final path segment of environment directory).
__VENV_PROMPT__ is replaced with the prompt (the environment name surrounded by parentheses and with a following space)
__VENV_BIN_NAME__ is replaced with the name of the bin directory (either bin or Scripts ).
__VENV_PYTHON__ is replaced with the absolute path of the environment’s executable.
The directories are allowed to exist (for when an existing environment is being upgraded).
There is also a module-level convenience function:
venv. create ( env_dir , system_site_packages = False , clear = False , symlinks = False , with_pip = False , prompt = None , upgrade_deps = False ) В¶
Create an EnvBuilder with the given keyword arguments, and call its create() method with the env_dir argument.
New in version 3.3.
Changed in version 3.4: Added the with_pip parameter
Changed in version 3.6: Added the prompt parameter
Changed in version 3.9: Added the upgrade_deps parameter
An example of extending EnvBuilder В¶
The following script shows how to extend EnvBuilder by implementing a subclass which installs setuptools and pip into a created virtual environment:
This script is also available for download online.
Источник