-1

I do not understand the value of the env attribute in the Popen subprocess. I want to change the virtual environment of the python code I am running.

example

Suppose a file named subprocess_test.py which is run through virtual environment venv_main:

# subprocess_test.py

cmd = f"C:/home/._venv/Scripts/python example.py".split()
sp = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd="/home", env = "___________")
try:
    sp.wait(timeout=16)
    run_output, run_error = sp.communicate()
except subprocess.TimeoutExpired:
    sp.kill()
    run_output, run_error = sp.communicate()

example.py

import os
print(os.environ)

It do not print the details of venv which Suprocess command takes .i.e, C:/home/._venv/Scripts instead It print the details of environment from which subprocess_test.py executes i.e., venv_main

Maybe env attribute can solve my problem But I do not understand how env attribute work and what is the appropriate value of env?

shraysalvi
  • 303
  • 1
  • 10

1 Answers1

0

The env argument should be a dictionary where the key is the env var name. In general you want to make a copy of os.environ then modify it (e.g., by changing the value of PATH) to suit your needs. This is a FAQ. See, for example, this stackoverflow question.

Kurtis Rader
  • 6,734
  • 13
  • 20