Skip to content

Instantly share code, notes, and snippets.

@kennethreitz
Created March 9, 2010 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennethreitz/327196 to your computer and use it in GitHub Desktop.
Save kennethreitz/327196 to your computer and use it in GitHub Desktop.
Random Python helper functions
# encoding: utf-8
""" Python General Helpers
Copyright (c) 2010 Kenneth Reitz. Creative Commons Attribution 3.0 Lisense.
"""
import urllib, re, time
import paramiko
def enc(str):
"""Encodes a string to ascii"""
return str.encode('ascii', 'ignore')
def dec(str):
"""Decodes a string to ascii"""
return str.decode('ascii', 'ignore')
def get_file(path):
"""Returns a file as a string"""
return open(path, 'r').read()
def get_file_lines(path):
"""Returns a file as a list of strings"""
return open(path, 'r').readlines()
def get_http(uri):
"""Fetches a file over http as a string"""
return urllib.urlopen(uri).read()
def get_http_lines(uri):
"""Fetches a file over http as a file object"""
return urllib.urlopen(uri).readlines()
def get_sftp(hostname, username, password, filename):
"""Fetches a file over sftp as a string
Note: Server must be in known_hosts.
"""
client = paramiko.SSHClient()
client.load_host_keys(keysPath=None)
client.connect(hostname=hostname, username=username, password=password)
file = client.open_sftp().open(filename).read()
log("Download of %s complete" % filename)
return file
def filename_from_url(url):
"""Returns filename from url"""
search = "(\w|[-.])+$"
return re.search(search, url).group()
def sql_datetime():
"""Returns SQL DateTime NOW() string"""
return str(time.strftime("%Y-%m-%d %H:%M:%S"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment