0

Is there any way I can activate my virtual environment and run some process using that environment with a single call to subprocess.Popen with shell=False?

For example I need to run the following command via subprocess

. myvenv/bin/activate && robot myrobotscript.robot,

because I want to use the Robot Framework package from my virtual environment. I don't need a secure implementation so setting shell=True wasn't a problem for me until I wanted to set a timeout for my process. Calling subprocess.kill(), however, doesn't kill the child process and so the timeout is literally useless. That is, because when calling process.communicate() with no timeout afterwars the behavior is the same as if I never passed a timeout to the method at all.

elsamuray7
  • 79
  • 1
  • 10
  • https://stackoverflow.com/search?q=activate+%5Bvirtualenv%5D+subprocess – phd Feb 26 '21 at 13:52
  • 1
    You don't need to activate the environment, you just need to run `python` from that environment. That is, instead of `. myvenv/bin/activate && robot myrobotscript.robot` run `myvenv/bin/python robot myrobotscript.robot` – phd Feb 26 '21 at 13:53
  • @phd I’ve read through multiple discussions that stated that this is actually not the same because when activating the environment some environment variables will be set which aren’t set when I just run python from the environment. Didn’t find anything about what difference it exactly makes, though. – elsamuray7 Feb 26 '21 at 17:25
  • The only changed env var is `$PATH`. If you not gonna run `python` or `pip` from you scripts there is no difference if you activate virtual env or use `myvenv/bin/python`. If you gonna run `python` or `pip` you'd better use `sys.executable` instead of relying on `$PATH`. – phd Feb 26 '21 at 18:05
  • @php I am using pip too. I tried `sys.executable` but that is always `usr/bin/python3` for me (also when I run python from the virtual environment). How can I make sure that it points to my virtual environment python? – elsamuray7 Feb 26 '21 at 20:02
  • Using a bash script: https://stackoverflow.com/a/6944649/7976758 Run it using single call to `subprocess`; activate the venv in the script and run everything else in it. – phd Feb 26 '21 at 20:53
  • Principally there are only 2 ways to activate a venv: prepend `myvenv/bin` to `PATH` in environment (the modified environment can be passed to `subprocess.Popen()`) or run `myvenv/bin/python` directly. Any solution at the linked dup or in the search results is just a syntactic sugar over these two. – phd Feb 26 '21 at 21:51
  • @phd I've used the `path/to/virtualenv/robot` solution for Robot Framework now, for pip however I am okay with `shell=True` since I don't expect pip to run forever and hence don't need the timeout there. Thanks for your help! – elsamuray7 Mar 01 '21 at 08:17

0 Answers0