问题
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?
回答1:
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
.
回答2:
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
回答3:
create wrapper file like below works for me, but little bit hacky way.
import subprocess
if __name__ == '__main__':
subprocess.run(['pipenv', 'run', 'foo'])
来源:https://stackoverflow.com/questions/51968643/how-to-use-pipenv-in-python-shell-script