Skip to content

Instantly share code, notes, and snippets.

@vsajip
Created July 13, 2013 14:08
Show Gist options
  • Save vsajip/5990837 to your computer and use it in GitHub Desktop.
Save vsajip/5990837 to your computer and use it in GitHub Desktop.
A simple script to bootstrap setuptools and pip into a Python environment which doesn't have them.
#
# Copyright (C) 2013 Vinay Sajip. New BSD License.
#
import argparse
import os
import shutil
from subprocess import Popen, PIPE
import sys
import tempfile
from threading import Thread
from urllib.parse import urlparse
from urllib.request import urlretrieve
def main(args=None):
def reader(stream, verbose):
"""
Read lines from a subprocess' output stream and either pass to a progress
callable (if specified) or write progress information to sys.stderr.
"""
while True:
s = stream.readline()
if not s:
break
if not verbose:
sys.stderr.write('.')
else:
sys.stderr.write(s.decode('utf-8'))
sys.stderr.flush()
stream.close()
def install_script(workdir, name, url, verbose):
_, _, path, _, _, _ = urlparse(url)
fn = os.path.split(path)[-1]
distpath = os.path.join(workdir, fn)
urlretrieve(url, distpath)
if verbose:
term = '\n'
else:
term = ''
sys.stderr.write('Installing %s ...%s' % (name, term))
sys.stderr.flush()
args = [sys.executable, fn]
p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=workdir)
t1 = Thread(target=reader, args=(p.stdout, verbose))
t1.start()
t2 = Thread(target=reader, args=(p.stderr, verbose))
t2.start()
p.wait()
t1.join()
t2.join()
sys.stderr.write('done.\n')
parser = argparse.ArgumentParser(description='Bootstrap setuptools and '
'pip.')
parser.add_argument('-v', '--verbose', default=False, action='store_true',
help='Display output from subcommands')
options = parser.parse_args()
workdir = tempfile.mkdtemp()
try:
try:
import setuptools
print('setuptools already available.')
except ImportError:
url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
install_script(workdir, 'setuptools', url, options.verbose)
try:
import pip
print('pip already available.')
except ImportError:
url = 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py'
install_script(workdir, 'pip', url, options.verbose)
finally:
shutil.rmtree(workdir)
if __name__ == '__main__':
rc = 1
try:
main()
rc = 0
except Exception as e:
print('Error: %s' % e, file=sys.stderr)
sys.exit(rc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment