Nifty Python Code Snippets
Convert seconds to minutes and hours
sec = 130823 h,s = divmod(sec,3600) m,s = divmod(s,60) print "%02.fh %02.fm %02.fs" % (h, m, s)
Strip off newlines in all elements of a list
list = [element.rstrip('\n') for element in list]
Run an external command and return the return code, stdout and stderr
run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait for the process to return
returncode = run.wait()
stdout = run.stdout.readlines()
stderr = run.stderr.readlines()
# Strip newlines at the end of each line
stdout = [line.rstrip('\n') for line in stdout]
stderr = [line.rstrip('\n') for line in stderr]
Read from STDIN
import sys for line in sys.stdin: line = line.strip() print line
Yes, sys.stdin is a file handle.
Reading from a MySQL database into a dictionary
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", port=3306, user="...", passwd="...", db="...")
cursor = db.cursor(MySQLdb.cursors.DictCursor)
sql = "select * from mytable"
cursor.execute(sql)
for row in iter(cursor.fetchone, None):
print row
If you omit the MySQLdb.cursors.DictCursor you will get the result in an array without knowing the column descriptions.
Parsing options from the command line
except getopt.error, why:
print 'getopt error: %s\n%s' % (why, usage)
sys.exit(-1)
try:
for opt in opts:
if opt[0] == '-h' or opt[0] == '--help':
print usage
sys.exit(0)
if opt[0] == '-p' or opt[0] == '--port':
port = int(opt[1])
Fetch a URL using a custom User-Agent header
import urllib2,re
url="http://google.com"
user_agent="Mozilla/5.0 (X11; U; Linux i686; de; rv:1.6) Gecko/20040113"
request = urllib2.Request(url)
opener = urllib2.build_opener()
request.add_header('User-Agent', user_agent)
html = opener.open(request).read()
