Update: I decided the below documentation is a bit naff, so I submitted a PR with some changes, and they were accepted! Check it out – https://pipenv.readthedocs.io/en/latest/advanced/#custom-script-shortcuts
From the documentation:
Custom Script Shortcuts
Pipenv supports to customize shortcuts in the scripts
section. pipenv run
will automatically load it and find the correct command to replace with. Given the Pipfile:
[scripts]printfoo = "python -c \"print('foo')\""[scripts] printfoo = "python -c \"print('foo')\""[scripts] printfoo = "python -c \"print('foo')\""
Enter fullscreen mode Exit fullscreen mode
You can type in your terminal to run:
$ pipenv run printfoofoo$ pipenv run printfoo foo$ pipenv run printfoo foo
Enter fullscreen mode Exit fullscreen mode
/end documentation
And it’s really that simple! It runs the script you give it with the pipenv virtual environment context whether you have your pipenv shell activated or not. I have found this super useful for running tests, individual modules, and custom commands.
For example, I use the autopep8 library so I can keep my whitespacing beautiful without the elbow grease of adding extra lines manually, so I have this line in the [scripts]
section of my Pipfile:
pep8 = "autopep8 -riv --max-line-length 150"pep8 = "autopep8 -riv --max-line-length 150"pep8 = "autopep8 -riv --max-line-length 150"
Enter fullscreen mode Exit fullscreen mode
With this, I can run pipenv run pep8 <file or directory name>
and poof! one line at the end of each file, two lines between functions, one line between methods, etc. (Note: I do not actually think 150 is a good max line length, I just don’t love where the tool auto-breaks lines, so I’d rather make those choices manually.)
Caveats
As far as I can work out, anything that you could run in your terminal with your pipenv shell activated will work, with the notable exeption that you can’t chain commands. I have not been able to get &&
, ||
, or ;
to work. This doesn’t really bother me, because if you really need to make a multiple command script, you can make an actual script file and run that from [scripts]
.
For example, I have a somewhat complex script running my test suite (mostly to add color) and I have a test.sh
file in the scripts/
directory. This is what I have in my Pipfile:
[scripts]tests = "./scripts/test.sh"[scripts] tests = "./scripts/test.sh"[scripts] tests = "./scripts/test.sh"
Enter fullscreen mode Exit fullscreen mode
I type pipenv run tests
and so it does.
If you’ve not been using this feature of pipenv, give it a try! Let me know what you end up using it for =)
If you’ve not switch to using pipenv yet, consider this a bit of incentive. I just switched this project from requirements.txt
and virtualenv/pyenv and it was not bad at all. It took a bit of persistence to hunt down all the necessary changes in our continuous integration / deployment system, but the changes themselves were not difficult.
Cheers 🥂️
暂无评论内容