Report #14790
[bug\_fix] bash: bad interpreter: No such file or directory or ModuleNotFoundError for venv packages due to shebang hardcoding after relocation
Recreate the virtual environment in the new absolute path to regenerate scripts with correct shebangs, or explicitly invoke the interpreter \(\`python script.py\`\) instead of \`./script.py\`, avoiding reliance on the shebang line which contains the old absolute path.
Journey Context:
Developer creates a virtual environment with \`python3 -m venv myenv\` at \`/home/user/projects/myenv\`, installs packages, and writes a script \`run.py\` with shebang \`\#\!/usr/bin/env python3\`. They activate the venv and run \`./run.py\` successfully. Later, the project directory is moved to \`/opt/app/\` \(e.g., in a Docker build or CI artifact\), or copied to a colleague's machine at \`/Users/colleague/projects/\`. Developer activates the moved venv with \`source myenv/bin/activate\` and runs \`./run.py\`, but gets \`bash: ./run.py: /home/user/projects/myenv/bin/python3: bad interpreter: No such file or directory\`. Even if they use \`python run.py\`, they might get \`ModuleNotFoundError\` for packages installed in the venv because \`which python\` points to system \`/usr/bin/python\` instead of the venv's binary \(since the activate script's shebangs or path munging failed\). The rabbit hole involves inspecting \`head -n1 myenv/bin/pip\` and seeing the hardcoded absolute path to the original Python binary. Realization hits that \`venv\` creates executables with absolute shebangs pointing to the interpreter used to create the environment for reproducibility. When the directory moves, these shebangs break. The fix is not to try to \`sed\` replace all shebangs \(fragile\), but to treat venvs as non-relocatable and simply recreate the environment in the new location \(\`python3 -m venv myenv\` at \`/opt/app/\`\), reinstalling requirements via \`requirements.txt\`. Alternatively, if the venv must be used temporarily without recreation, one must explicitly call the intended Python binary with the full path \`/opt/app/myenv/bin/python script.py\` rather than relying on shebangs or the broken \`activate\` script's PATH manipulation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T22:24:36.688490+00:00— report_created — created