How to run a command inside virtual environment using Python
<p>I have the virutalenv created and installed. I have also installed jsnapy tool inside my virutal env. </p>

<p>This is the script that we are using:</p>

<pre><code>Filename : venv.py 
import os
os.system('/bin/bash  --rcfile ~/TestAutomation/End2EndAutomation/bin/activate')
os.system('End2EndAutomation/bin/jsnapy')

ubuntu@server:~/TestAutomation$ python venv.py
(End2EndAutomation) ubuntu@sdno-server:~/TestAutomation$ ^C
</code></pre>

<p>We need to know, is how we can get into virutalenv, run a command and deactivate it using python script?</p>

<p>[EDIT1]</p>

<p>i used the code given in the comment. its just entering virutal env. When i issue exit, its running jsnapy command. </p>

<pre><code>ubuntu@server:~/TestAutomation$ python venv.py
(End2EndAutomation) ubuntu@server:~/TestAutomation$ exit
exit
usage:
This tool enables you to capture and audit runtime environment of
networked devices running the Junos operating system (Junos OS)

Tool to capture snapshots and compare them
It supports four subcommands:
 --snap, --check, --snapcheck, --diff
1. Take snapshot:
        jsnapy --snap pre_snapfile -f main_configfil
</code></pre>

<p>Two successive calls to <code>os.system()</code> will create two independent processes, one after the other.  The second will run when the first finishes.  Any effects of commands executed in the first process will have been forgotten and flushed when the second runs.</p>

<p>You want to run the activation and the command which needs to be run in the virtualenv in the same process, i.e. the same single shell instance.</p>

<p>To do that, you can use <code>bash -c '...'</code> to run a sequence of commands.  See below.</p>

<p><strong>However,</strong> a better solution is to simply activate the virtual environment from within Python itself.</p>

<pre><code>p = os.path.expanduser('~/TestAutomation/End2EndAutomation/bin/activate_this.py')
execfile(p, dict(__file__=p))
subprocess.check_call(['./End2EndAutomation/bin/jsnapy'])
</code></pre>

<p>For completeness, here is the Bash solution, with comments.</p>

<pre><code>import subprocess
subprocess.check_call(['bash', '-c', """
    . ~/TestAutomation/End2EndAutomation/bin/activate
    ./End2EndAutomation/bin/jsnapy"""])
</code></pre>

<p>The preference for <code>subprocess</code> over <code>os.system</code> is recommended even in the <a href="https://docs.python.org/2/library/os.html#os.system" rel="nofollow"><code>os.system</code> documentation</a>.</p>

<p>There is no need to explicitly <code>deactivate</code>; when the <code>bash</code> command finishes, that will implicitly also deactivate the virtual environment.</p>

<p>The <code>--rcfile</code> trick is a nice idea, but it doesn't work when the shell you are calling isn't interactive.</p>

python