Wednesday, July 17, 2013

Python code snippets

EXCELLENT COVERAGE OF MATPLOTLIB
http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-4-Matplotlib.ipynb

ZIP A LIST INTO SUBGROUPS
izip(*[iter(l)]*size)
zip(*[imap(func)]*size)
 
http://stackoverflow.com/questions/4628290/pairs-from-single-list

BETTER EXAMPLE CONTROLLING SSH WITH PEXPECT AND PXSSH 
#!/usr/bin/env python
import pxssh
def getLine(password="password", hostname="host"):
        try:
                s = pxssh.pxssh()
                username = "root"
                s.login (hostname, username, password)
                s.sendline ("echo 'Hello World'")  # run a command
                s.prompt()             # match the prompt
                line = s.before
                s.logout()
                return line
        except pxssh.ExceptionPxssh, e:
                print "pxssh failed on login."
                print str(e)

print getLine()


EXAMPLE OF CONTROLLING SSH IN PURE PYTHON WITH CORE LIBS
#!/usr/bin/env python
import pty
import os
import sys
import time
pid,fd = pty.fork()
if pid==0:
    os.execv("/usr/bin/ssh",["/usr/bin/ssh","root@host","echo 'Hello World!' | awk '{print $2}'"])
else:
    password = 'password\n'
print "Child says",os.read(fd,1024).strip()
print "Child took",os.write(fd,password)
time.sleep(1)
print "Child says",os.read(fd,1024).strip()
#SSH uses pty instead of stdin to communicate
#http://www.gossamer-threads.com/lists/python/python/56425