Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stay inside virtual environment when using subprocesses?

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

like image 935
Anna Avatar asked Nov 05 '25 14:11

Anna


1 Answers

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:

  • https://docs.python.org/3/library/sys.html#sys.executable
  • https://docs.python.org/3/library/subprocess.html#subprocess.run
like image 127
sinoroc Avatar answered Nov 08 '25 10:11

sinoroc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!