Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pipenv in Python shell script?

I needed a module for a shell script I've written in Python, so I used pipenv to install it. I can run the command fine using:

~$ pipenv run python3 foo

Now, if I want to just run ~$ foo on the command line (fish shell on MacOS, homebrew installed), how do I invoke the pipenv environment in the shebang of my Python script? Or is there a better way?

like image 995
gtcaz Avatar asked Aug 22 '18 14:08

gtcaz


2 Answers

As documented here https://pipenv.readthedocs.io/en/latest/ you need to activate the virtual environment first. This will spawn another shell with the virtual environment activated

$ pipenv shell

so that you can run

$ python foo

to execute your script. Then you can use

#!/usr/bin/env python

on the first line of your script and make the script executable (chmod +x foo.py) so that you can run

$ ./foo

If the location of that script is part of your PATH environment variable, you should be able to run now

$ foo.py

If you don't like the extension you will have to remove from your script too

like image 73
PinoSan Avatar answered Nov 14 '22 19:11

PinoSan


With pipenv-shebang you can run your script with

pipenv-shebang PATH/SCRIPT

or you could insert the shebang

#!/usr/bin/env pipenv-shebang

to run it with just PATH/SCRIPT.

like image 26
laktak Avatar answered Nov 14 '22 17:11

laktak