Search code examples
pythonpython-venv

Does renaming project folder break venv in python?


This below is happened to me today, and I wondered the question as title says.

  1. Create python project folder
  2. Create virtual environment with venv command inside the folder.
  3. Rename the project folder name.
  4. Reload VSCode.
  5. .venv\Scripts\activate.bat seems not working. I see (.venv) in terminal, but where pip shows Systems's python.exe not inside .venv folder.

I searched about venv but im not sure i perfectly understand that, so with this question I want to be sure my understanding is correct.

thanks for reading.


Solution

  • Yes. There are hardcoded values in the generated files of the virtual environment.

    I'm on linux, which uses . venv/bin/activate to start a virtual environment, and you'll find in it a line like so:

    ...
    VIRTUAL_ENV="/home/someuser/programs/someprogram/venv"
    ...
    

    If I moved that venv, this line of the activate file would no longer point at it, causing it to be broken.

    It is the same for windows. They don't support renaming or otherwise moving the location of the virtual environment.


    edit

    I found a copy of the windows activate.bat online, and it looks like it doesn't hard code anything in there.

    I grepped my venv, and found a number of other files that contained hardcoded paths, so I expect my original statement will remain accurate even if the specific activate file lacks hardcoding.