Skip to content

Instantly share code, notes, and snippets.

@zhasm
Created December 28, 2010 08:59
Show Gist options
  • Save zhasm/757071 to your computer and use it in GitHub Desktop.
Save zhasm/757071 to your computer and use it in GitHub Desktop.
useful python snippets
def alert(msg):
'''return javascript alert window with givin message'''
return '''<script type="text/javascript" charset="utf-8">
alert("%s");
</script>''' % msg
from os.path import dirname as dirname
from os.path import join as pathjoin
def getPath(sufix=""):
'''get absolute path of the current dir'''
path = dirname(__file__)
try:
index=path.index("..")
if index!=-1:
path=path[:index]
except:
pass
return pathjoin(path, sufix).replace('\\','/')
#force utf8
import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
from hashlib import md5
def md5ize(s):
'''return the md5 encoding of a string'''
return md5(s).hexdigest()
#integer file size to stringG
def format_size(size):
if size<1024:
return "%s Byte"% size
elif size>=1024 and size <1024*1024:
size /=1024
return "%s Kb"% size
elif size>=1024*1024 and size <1024*1024*1024:
size /=(1024*1024)
return "%s Mb"% size
#get parameter from url:
def get_V(p, regex=None):
"""return cgi GET parameter; strip white spaces at both ends if any;
if verify pattern provided, do match test; only return matched values.
Note: it uses re.match to check , not re.search.
"""
import cgi
form = cgi.FieldStorage()
value= form.getfirst(p)
if not value:
return None
value=value.strip()
if regex is not None:
import re
if re.match(regex+"$",value):
return value
else:
return None
else:
return value
def stringio():
buffer = StringIO.StringIO()
buffer.truncate(0)
c.setopt(c.WRITEFUNCTION, buffer.write)
value=buffer.getvalue()
def Do(cmdstr):
from commands import getoutput
try:
return getoutput(cmdstr)
except Exception, e:
return str(e)
#sending email via local bash.
def Notify(content, receiver):
from commands import getoutput as Do
if not content:
return
subject="fanfou @ v2ex update"
print content
command="""mail -a "From: [email protected]" -s "%s" "%s" <<< "%s" """ % (subject, receiver, content)
try:
Do(command)
except Exception, e:
print str(e),"error!"
import urllib
def getHeader(url):
'''get header information of a url'''
remotefile=urllib.urlopen(url)
return remotefile.headers.dict
def getRemoteFileLength(url, unit='k'):
'''get length of an remote file, without downloading that file.'''
remotefile=urllib.urlopen(url)
unit=unit.upper()
units={
'B':1,
'K':1024,
'M':1024*1024,
'G':1024*1024*1024,
}
try:
length=remotefile.headers.dict['content-length']
except:
print 'no length infor. loading complete file to caclulate length'
length=len(remotefile.read())
reallen=float( float(length) / units[unit])
formatedLength = "%.2f%s" % (reallen,unit)
return formatedLength
#escaping html
html_escape_table = {
"&": "&amp;",
'"': "&quot;",
"'": "&apos;",
">": "&gt;",
"<": "&lt;",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment