'Is there a single line way to run a command in a Python venv?

I have a command that only runs correctly inside a Python virtual environment I've configured (as intended). I know that I can run the command as

$ cmd args

once I've activated the venv. But (due to the constraints of the tool I'm using) I need to activate run (and deactivate?) in one line: something equivalent to running

$ activate_somehow cmd args

outside the command line.

Is there a way to do this?



Solution 1:[1]

You can generally run something in a virtual environment simply by using a fully qualified path to the script. For example, if I have:

virtualenv .venv

Then I can install something into that virtual environment without activating it by running:

.venv/bin/pip install foo

This should be true for anything installed using standard Python mechanisms.

Solution 2:[2]

After looking into the generated bin/activate script, it seems like the only thing relevant to python is the VIRTUAL_ENV variable, so this should be enough to get going:

$ env VIRTUAL_ENV=path/to/venv python ...

Note that the python executable in the bin directory of target environment is just a symlink to globally installed interpreter, which does nothing other that setting process executable path. Assuming the program does not make use of it, utilizing the main binary itself seems harmless. In case you have installed a package which in turn installs some executables, just specify the absolute path:

$ env VIRTUAL_ENV=path/to/venv path/to/venv/bin/executable

Solution 3:[3]

I found venv-run which should do what you ask:

pip install venv-run
venv-run cmd args

Solution 4:[4]

You can create a simple wrapper script which runs activate, executes your command, and then deactivates simply by exiting the script in which your environment was activated.

#!/bin/sh
. ${venv-./env}/bin/activate
"$@"

This lets you set the environment variable venv to the path of the environment you want to use, or else uses ./env if it is unset. Perhaps a better design would be to pass the env as the first parameter:

#!/bin/sh
. "$1"/bin/activate
shift
"$@"

Either way, save this somewhere in your PATH ($HOME/bin is a common choice for your private scripts) and give it executable permission.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks
Solution 2 Mohammad Amin Sameti
Solution 3 quadratecode
Solution 4