pythonsubprocessloadlibrary

How to avoid loading wrong libraries when using a subprocess.Popen() from a python script to run a venv?


I want to run a script using a venv python~3.9 from a subprocess call of another application that uses python3.6. However the imported libraries are wrong and from the site-packages of 3.6 version. How can I modify the subprocess call to load the correct libraries i.e from the venv(3.9 version)

p = Popen([process_name, parameters_l], stdin=PIPE, stdout=PIPE, stderr=PIPE)

I have tried using the cwd and also changing the working directory via os.chdir however that doesn't seem to work. Furthermore I tried to run activat.bat from the venv, but the issue persists.


Solution

  • In order to solve the issue I had to get the current environment and delete some variables e.g:

    env = os.environ.copy()
    del env["PYTHONPATH"]
    
    Popen([process_name, parameters_l], env=env)
    

    Finally use the new env in the subprocess call as a parameter. Hope it helps if anyone is facing a similar situation.