2

I have a python script that is running in virtual environment. I needed this code to invoke another python script. For that I used subprocess.call(['python', 'python_script.py']), but the python_script is stuck at the imports, because it is running outside the virtual environment, and some of the modules are only available in venv.

What should I do to call subprocess and stay inside venv?

(BTW, I'm using Windows right now, but I am looking for a cross-platform solution)

EDIT: As I understood that behaviour I wanted was the default one, I've just deleted virtual environment and created the new one. Surprisingly, it worked. Still have no idea what was happening with the old venv, though

Anna
  • 199
  • 1
  • 10
  • How did you activate the virtual environment? Normally, `VIRTUAL_ENV` and `PATH` (the two key variables for running the virtual environment correctly, set by sourcing the `activate` script or whatever the Windows equivalent is) would be an exported environment variables, and the child process would use them (`PATH` to find `python` in the virtual environment, `VIRTUAL_ENV` to set up the environment once launched). – ShadowRanger Oct 29 '20 at 15:18
  • Does this answer your question? [Running subprocess within different virtualenv with python](https://stackoverflow.com/questions/8052926/running-subprocess-within-different-virtualenv-with-python) – Christopher Peisert Oct 29 '20 at 16:23
  • @ShadowRanger, this was my thought exactly. I used ```call venv\Scripts\activate.bat``` to activate virtual environment and I thought that child processes would stay in the same venv. Now I am curious about what happened – Anna Oct 30 '20 at 08:16
  • @ChristopherPeisert, unfortunately, no. This question is about switching to a different venv, as if the child process would by default run in the same venv as a parent process. However, in my situation this doesn't seem to be the case – Anna Oct 30 '20 at 08:19

1 Answers1

2

If I am not mistaken the following should get you on the right track:

import sys

subprocess.call([sys.executable, 'python_script.py'])

sys.executable will give you the currently running Python interpreter. Which means if you are already in a virtual environment, the subprocess will be in the virtual environment as well.

If the results are still not exactly as you expect, you might want to look into forwarding some environment variables explicilty (VIRTUAL_ENV and PATH for example), although it should not be necessary.

References:

sinoroc
  • 18,409
  • 2
  • 39
  • 70