virtualenvvirtualenvwrapper

After "deactivate" from virtualvenv, prompt has "if defined _OLD_VIRTUAL_PYTHONPATH (set "PYTHONPATH=" ) "


I have a python (3.11) virtual env named "Test". Using VSC, Command "Workon Test" puts me in the Test virtual env. However, when I "deactivate", the command prompt has "if defined _OLD_VIRTUAL_PYTHONPATH (set "PYTHONPATH=" ) followed by the correct command prompt as expected (C:\Users\ksarn\ENVS>).

C:\Users\ksarn\ENVS>pip list
Package               Version
--------------------- -------
distlib               0.3.6  
filelock              3.8.0  
pip                   22.3.1 
platformdirs          2.5.4  
setuptools            65.5.0 
virtualenv            20.16.7
virtualenvwrapper-win 1.2.7

C:\Users\ksarn\ENVS>workon test
(test) C:\Users\ksarn\ENVS>whereis python
C:\Users\ksarn\ENVS\test\Scripts\python.exe

(test) C:\Users\ksarn\ENVS>deactivate

C:\Users\ksarn\ENVS>if defined _OLD_VIRTUAL_PYTHONPATH (set "PYTHONPATH=" ) 
C:\Users\ksarn\ENVS>

C:\Users\ksarn\ENVS>whereis python
C:\Users\ksarn\AppData\Local\Programs\Python\Python311\python.exe

C:\Users\ksarn\ENVS>

Why is it showing set "Python path statement?

Re-installed python 3.11 (with path selected), virtualenv and virtualenvwrapper-win. No change.


Solution

  • I had the same problem. What worked for me in Windows is editing the routine that creates each environment.

    1. Find and go the folder where default python is installed, which is used as base for virtualenv, e.g., C:\Users\<UserName>\AppData\Local\Programs\Python\Python311 (user only installation).

    2. Secondary click > Edit on the file \Scripts\mkvirtualenv.bat

    3. Search for "_OLD_VIRTUAL_PYTHONPATH" (about in the middle of the file) and write the @ character to mute each command to be written in activate.bat and deactivate.bat. The result should look something like this:

      :: In activate.bat, keep track of PYTHONPATH.
      :: This should be a change adopted by virtualenv.
      >>"%WORKON_HOME%\%venvwrapper.quoteless_envname%\Scripts\activate.bat" (
          echo.:: In case user makes changes to PYTHONPATH
          echo.@if defined _OLD_VIRTUAL_PYTHONPATH (
          echo.    @set "PYTHONPATH=%%_OLD_VIRTUAL_PYTHONPATH%%"
          echo.^) else (
          echo.    @set "_OLD_VIRTUAL_PYTHONPATH=%%PYTHONPATH%%"
          echo.^)
      )
      
      :: In deactivate.bat, reset PYTHONPATH to its former value
      >>"%WORKON_HOME%\%venvwrapper.quoteless_envname%\Scripts\deactivate.bat" (
      echo.
      echo.@if defined _OLD_VIRTUAL_PYTHONPATH (
      echo.    @set "PYTHONPATH=%%_OLD_VIRTUAL_PYTHONPATH%%"
      echo.^)
      )
      
    4. Save the file and re-create any environment tha had the problem. It shouldn't verbose any command.

    As an alternative, you can edit directly edit the activate.bat and deactivate.bat files for each environment within its \Scripts\ subfolder.