from io import StringIO from pip import main import sys sysout = StringIO() syserr = StringIO() class redirect: """Context manager for temporarily redirecting stdout/err. Simplified and generalize from contextlib.redirect_stdout. """ def __init__(self, stdfile, new_target): self._stdfile = stdfile # 'stdout' or 'stderr' self._new_target = new_target def __enter__(self): self._old = getattr(sys, self._stdfile) setattr(sys, self._stdfile, self._new_target) return self._new_target def __exit__(self, exctype, excinst, exctb): setattr(sys, self._stdfile, self._old) # For GUI version, redirects would be here, done once. # Put in runpip for prototype testing in text mode, so can print. def runpip(argstring): '''Run pip with argument string containing command and options. Argstring is quoted version of what would follow 'pip' on command line. ''' with redirect('stdout', sysout) as f1, redirect('stderr', syserr) as f2: status = main(argstring.split()) out = sysout.getvalue() err = syserr.getvalue() sysout.seek(0); sysout.truncate(0) syserr.seek(0); syserr.truncate(0) return status, out, err # example usage package = 'pip' stat, out, err = runpip('show %s'%package) print('stat: {}\n\n{}\nerr: {}'.format(stat, out, err)) #prints ##stat: 0 ## ##--- ##Metadata-Version: 2.0 ##Name: pip ##Version: 7.1.2 ##Summary: The PyPA recommended tool for installing Python packages. ##Home-page: https://pip.pypa.io/ ##Author: The pip developers ##Author-email: python-virtualenv@groups.google.com ##License: MIT ##Location: c:\programs\python34\lib\site-packages ##Requires: ## ##err: