from __future__ import absolute_import, unicode_literals

# Fix error message: Exception KeyError ... in <module 'threading' ...
import sys
if 'threading' in sys.modules:
    del sys.modules['threading']
import gevent
import gevent.socket
import gevent.monkey
gevent.monkey.patch_all()
# END

from pssh import ParallelSSHClient

from .output import Output


class RemotePip(ParallelSSHClient):

    def __init__(self, hosts, pip_path='/usr/bin/pip', *args, **kwargs):
        self.pip_path = pip_path
        self.output = None
        super(RemotePip, self).__init__(hosts, *args, **kwargs)

    def install(self, pkgs, upgrade=False):
        cmd = self.generate_install_cmd(pkgs=pkgs, upgrade=upgrade)
        output = self.run_command(cmd)
        self.output = Output.from_pssh_dict(output)
        return self.output

    def generate_install_cmd(self, pkgs, upgrade=False):
        cmd = '{} install '.format(self.pip_path)

        if isinstance(pkgs, unicode):
            pkgs = [pkgs]
        cmd += ' '.join(pkgs)

        if upgrade:
            cmd += ' -U'
        return cmd


if __name__ == '__main__':
    hosts = ['54.210.23.215', '52.91.174.90', '54.172.180.200', '52.91.58.145']
    import paramiko
    key = paramiko.RSAKey.from_private_key_file('/Users/drodriguez/.ssh/drodriguez.pem')

    rpip = RemotePip(hosts, user='ubuntu', pkey=key, pip_path='/opt/anaconda/bin/pip')
    print rpip.generate_install_cmd(pkgs='requests')
    print rpip.install(pkgs='requests')

@@ -1089,402 +1089,439 @@
 md%0A%0A
-%0Aif __name__ == '__main__':%0A    hosts = %5B'54.210.23.215', '52.91.174.90', '54.172.180.200', '52.91.58.145'%5D%0A    import paramiko%0A    key = paramiko.RSAKey.from_private_key_file('/Users/drodriguez/.ssh/drodriguez.pem')%0A%0A    rpip = RemotePip(hosts, user='ubuntu', pkey=key, pip_path='/opt/anaconda/bin/pip')%0A    print rpip.generate_install_cmd(pkgs='requests')%0A    print rpip.install(pkgs='requests')
+    def uninstall(self, pkgs):%0A        cmd = self.generate_uninstall_cmd(pkgs=pkgs)%0A        output = self.run_command(cmd)%0A        self.output = Output.from_pssh_dict(output)%0A        return self.output%0A%0A    def generate_uninstall_cmd(self, pkgs):%0A        cmd = '%7B%7D uninstall '.format(self.pip_path)%0A%0A        if isinstance(pkgs, unicode):%0A            pkgs = %5Bpkgs%5D%0A        cmd += ' '.join(pkgs)%0A%0A        cmd += ' -y'%0A        return cmd
 %0A

Add uninstall