Skip to content

Instantly share code, notes, and snippets.

@turicas
Created June 8, 2012 19:23
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save turicas/2897697 to your computer and use it in GitHub Desktop.
Save turicas/2897697 to your computer and use it in GitHub Desktop.
Execute Python code in a virtualenv, return its stdout and stderr
#!/usr/bin/env python
# coding: utf-8
import os
import shlex
from subprocess import Popen, PIPE
def execute_in_virtualenv(virtualenv_name, commands):
'''Execute Python code in a virtualenv, return its stdout and stderr.'''
command_template = '/bin/bash -c "source {}/{}/bin/activate && python -"'
command = shlex.split(command_template.format(os.environ['WORKON_HOME'],
virtualenv_name))
process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
return process.communicate(commands)
if __name__ == '__main__':
from textwrap import dedent
virtualenv_name = 'pypln'
commands = dedent(r'''
import sys
try:
import rdfextras
print 'Imported successfully'
except:
print 'Cannot import'
sys.stderr.write('testing stderr\n')
''')
stdout, stderr = execute_in_virtualenv(virtualenv_name, commands)
print 'stdout:'
print stdout
print '\nstderr:'
print stderr
@LetUsFsck
Copy link

Im in such need for this on python3 heh. Thanks for the template, lets see if I can make it happen

@Rizwan-Hasan
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment