Virtual env PATH question

I constructed a virtual env, then moved its directory. (This is on a Mac, but the eventual target is a Linux host.) That failed, because VIRTUAL_ENV is hardcoded in the activate script:

export VIRTUAL_ENV=/Users/skip/py314

Is there some reason it can’t be defined in terms of the location of the activate script, something like:

export VIRTUAL_ENV=$(dirname $(dirname $0))

Personally I never use the activate scripts.
It’s easier to run the python inside the venv’s bin folder.
Would that work for you?

I have a venv on my mac that I use to run personal tools with and have a helper script like this:

% more ~/bin/tool-python3
#!/bin/bash
# run inside of the tools venv
exec ~/.local/tools.venv/bin/python3 "$@"

Running python3 that way works great and as you see no activate in sight.

Thanks for the reply. I suppose if all I ever ran was the Python interpreter that would be a solution. I have 50 or so available shell-level commands in mine though, from the interpreter to gunicorn, coverage and pytest.

Edit: One other thing. I have multiple virtual environments for different versions of Python. Currently, I have 3.14, 3.15 and 3.16 versions in my home directory. In my project directory, I have 3.10 thru 3.16, though I just officially updated my website’s Flask app to 3.15, so will probably trim the number there shortly.

The point is that by sourcing the activate script I can tell at a glance what interpreter version I will get when I type “python.”

(py316) ~/src/smontanaro.net%

In that case you can add the venv bin dir to your PATH and then you can run any command that is installed in the venv directly.

Since you’re targeting a Linux host anyway, moving the venv from macOS wouldn’t work even with a relocatable activate script: the interpreter symlinks, the home = path in pyvenv.cfg, any compiled wheels and the console-script shebangs are all tied to the machine and path where it was created.

The usual approach is to treat a venv as disposable and rebuild it at the destination:

pip freeze > requirements.txt          # on the Mac
python3 -m venv /path/on/linux/venv    # on the host
/path/on/linux/venv/bin/python -m pip install -r requirements.txt

If you only move it to another path on the same machine, recreating is still the safest option. As a quick hack you can edit the VIRTUAL_ENV= line in bin/activate, but scripts in bin/ will still have the old shebang.

I get that. I mean moving in within the same computer.

For all my venv’s I have a script that creates them so I don;t have to recall details.

Why not create a script then you can avoid needing to move a venv?