Last active
April 27, 2017 09:56
-
-
Save sakurai-youhei/c3b96ec2f698715ef5379872757d9240 to your computer and use it in GitHub Desktop.
Run pip programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
from contextlib import redirect_stdout as r_stdout | |
from contextlib import redirect_stderr as r_stderr | |
from io import StringIO | |
import pip | |
def pip_exec(*args): | |
with StringIO() as stdout, StringIO() as stderr: | |
with r_stdout(stdout), r_stderr(stderr): | |
code = pip.main(list(args)) | |
return code, stdout.getvalue(), stderr.getvalue() | |
def raise_on_nonzero(code, stdout, stderr, exc=RuntimeError): | |
if code: | |
raise exc("pip failed", code, stdout, stderr) | |
else: | |
return code, stdout, stderr | |
@contextmanager | |
def pip_install(*args): | |
raise_on_nonzero(*pip_exec("install", *args)) | |
yield | |
if __name__ == "__main__": | |
with pip_install("requests", "pyzmq"): | |
import requests | |
import zmq |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment