简体   繁体   中英

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?

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

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 .

create wrapper file like below works for me, but little bit hacky way.

import subprocess
if __name__ == '__main__':
    subprocess.run(['pipenv', 'run', 'foo'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM