CIsForCookies
CIsForCookies

Reputation: 12817

Shebang directing to specific virtualenv - is it a good idea?

I have a script for which I must have a specific virtualenv on.

Running the script with #!/usr/bin/env python / python3 / python3.6 will not cut it if the virtualenv is not on when the script runs, so I have done something like this:

#!/home/bla/bla2/bla3/venv/bin/python
import virtualenv stuff...

I assume that

  1. virtualenv will be installed beforehand
  2. the script / dir / venv will stay in the exact same place

Given those 2 assumptions, is this a good idea? If not, what would be better? I'm reluctant to having a wrapper bash script that would turn on the venv and then call my script

Upvotes: 5

Views: 2127

Answers (2)

sinoroc
sinoroc

Reputation: 22295

This is perfectly fine, this is how the console scripts for entry points are generated. Of course there are the limitations that files and directories can not be renamed, etc. but well that is quite obvious.

For example here is the content of the pip script in a freshly created virtual environment:

/tmp/tmp.cqz22j4Vg7$ cat .venv/bin/pip
#!/tmp/tmp.cqz22j4Vg7/.venv/bin/python3

# -*- coding: utf-8 -*-
import re
import sys

from pip._internal.cli.main import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

I believe the shebang in the scripts is an absolute path exactly so that they can be called without having to activate the virtual environment.

A common practice is to keep such a virtual environment around and add a symbolic link to a particular script in a directory listed in PATH. For example, one could install tox in a virtual environment and make it available from anywhere:

ln -s '/path/to/venv/bin/tox' "${HOME}/.local/bin/tox"

From Python's venv documentation:

There should be no need in other circumstances to activate a virtual environment; scripts installed into virtual environments have a “shebang” line which points to the virtual environment’s Python interpreter.

-- https://docs.python.org/3/library/venv.html?highlight=shebang

Upvotes: 3

Hack5
Hack5

Reputation: 3601

You should create a script that builds the venv and then runs the script inside it. Hardcoding the path to the venv python is a terrible idea, because if you change your username, PC, etc. or give someone else the code (or make it open source) it will fail.

Upvotes: 7

Related Questions