In 2021, when everyone uses pipenv and poetry, I realized that pyenv-virtualenv is perfect for a certain purpose, so I will introduce it.
It is one of the virtual environment construction tools of python. It is an extension of pyenv. In normal pyenv, the environment is controlled by specifying the version name prepared by the pyenv formula like pyenv local 3.8.7
, but if you use pyenv-virtualenv, you can use your favorite environment like pyenv local saishinban
. You can specify a name, and you can isolate the environment by this environment name.
There are many articles about pyenv-virtualenv in Qiita, so I'll just give you a rough explanation. If you want to know more, please refer to Official README and other articles.
You're probably writing in python the strongest CLI tools I've come up with for your hobbies and work. And, it seems that package management is done using poetry etc. in a modern way (2021). Let's say you have a tool like that. So how do you get this CLI tool to work?
To give you the answer right away, pyenv-virtualenv is perfect for the others in 4.
First, if 1, 2 and 3 fail, it will be as follows.
Case | problem |
---|---|
1. docker | CLI tools often handle local directories and files, which require mounting and authority management, which is troublesome and risky (badly)./ Mount and erase all files, etc.) |
2.Same as development | When using poetry or pipenv, it is necessary to go to that directory first and then operate it, which is troublesome (handling of CLI argument paths is also troublesome). |
3.system | Where did the dependency management go ... |
Well, if you do your best and ignore the risks, you can do it, but I don't want to do anything.
Create the pyenv-virtualenv environment as follows:
$ pyenv install X.X.X #Install your favorite version (not required if already installed)
$ pyenv virtualenv X.X.X mytoolenv
$ pyenv shell mytoolenv
$ pip install -e PATH/TO/mytool #Now install your strongest CLI tool (setup if using poetry).Without py,`pip install -e`Note that cannot be used)
Then, create a file with the same name as the tool name in a directory in your PATH (in the example, the tool name is mytool), write the following contents, and give execute permission.
#! /bin/bash
eval "$(pyenv init -)"
pyenv shell mytoolenv
mytool $*
Now, when you hit mytool, you can run it in a dedicated virtual environment. If you're trying to get rid of setup.py and you can't use pip install -e
, it's a good idea to have a script to reinstall.
The appeal of this method is that you can use the tools in any directory and still have a decent virtual environment (not as much as docker).
There are good cases to use pyenv-virtualenv even in 2021. If you are facing similar troubles, please consider it.
Recommended Posts