Saturday, October 30, 2021

[SOLVED] Running subprocess within different virtualenv with python

Issue

Let's say I have 2 different versions of my app installed in 2 different virtualenvironments. myapp v1.0 and myapp v2.0.

Now I would like to compare those. The comparison is written in python itself. What would be the best way to do that? Let's assume I can run them separately and both write an output file, which I can compare later.

One way to do that would be to write a bash script (that's what I have currently). I activate one virtualenv, run myapp v1.0, activate another virtualenv, run myapp v2.0. Later run a comparison module on those files. But I would like to add some more dynamics there (take some optional arguments etc) which would be easier with python.

Edit:

Currently I have something like that (a bash script):

source virtualenv1/bin/activate
python my_script.py
deactivate

source virtualenv2/bin/activate
python my_other_script.py
deactivate

python my_comparison_script.py

instead, I'd like to do only:

python my_comparison_script.py

and my scripts would be run inside this.


Solution

what exactly is the question? how to use subprocess to execute shell commands? if that's the case, some simplistic pseudo code might look like:

import subprocess

myProcess = subprocess.Popen(   ['these', 'are', 'for', 'the', 'shell'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE )

[outStream, errStream] = myProcess.communicate()

then you can do whatever you'd like with standard out (outStream) and do different things if errStream exists (standard error). this includes writing the standard out or standard error to a file. then i presume you would diff those files?

an actual code example (assuming you have python 2.6+ on a linux system) might look like:

import subprocess

with open('dateHelp.log', 'w') as dateLog:
    with open('dateHelp.err', 'w') as errLog:
        dateHelp = subprocess.Popen([ 'date', '-h'], stdout=dateLog, 
                                                     stderr=errLog)
        dateHelp.communicate()


Answered By - aeroNotAuto