Public
snipts » python
showing 1-20 of 219 snipts for python
-
∞ send email
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. textfile = 'result.txt' fp = open(textfile, 'rb') # Create a text/plain message msg = MIMEText(fp.read()) fp.close() me = 'joshua.java@gmail.com' recipients = ['thejavafreak@yahoo.com'] msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('smtp.server') #s.connect() for recipient in recipients: msg['To'] = recipient s.sendmail(me, recipient, msg.as_string()) s.quit()
-
∞ absolute directory path in python
# Find current directory DIR_ROOT = os.path.dirname(os.path.abspath(__file__)) # Absolute path for subfolder(s) LOG_ROOT = os.path.join(DIR_ROOT, 'logs')
-
∞ django groups and permissions
from django.contrib.auth.models import Group, Permission special_users = Group(name='Special Users') special_users.save() really_special_users = Group(name='Super Special Users') really_special_users.save() #Now you have two groups defined and can define permissions for them. Django associates #permissions with models (note: not model instances, but models). You’ll need to select a #model to apply the permissions to, and do a small dance with “ContentType” to find that #model’s content type: from django.contrib.contenttypes.models import ContentType somemodel_ct = ContentType.objects.get(app_label='myapp', model='somemodel') can_view = Permission(name='Can View', codename='can_view_something', content_type=somemodel_ct) can_view.save() can_modify = Permission(name='Can Modify', codename='can_modify_something', content_type=somemodel_ct) can_modify.save() #You’ve now defined two permissions and can associate them with your Groups: special_users.permissions.add(can_view) really_special_users.permissions = [can_view, can_modify] #Our groups and their associated permissions are ready to go. Now we just have to #associate these permissions with users: jack=User.objects.get(email='jack@test.com') jack.groups.add(special_users) jill=User.objects.get(email='jill@test.com') jill.groups.add(really_special_users) #We're all done. Now we can check the users' permissions: >>> jack.has_perm('myapp.can_view_something') True >>> jack.has_perm('myapp.can_modify_something') False >>> jill.has_perm('myapp.can_view_something') True >>> jill.has_perm('myapp.can_modify_something') True #And to use it in your templates: {% if perms.myapp.can_view_something %} Here is something for you to see. {% else %} Can't show you! {% endif %}
-
∞ I hate you so mych Django, with your custom non-strftime date formatting.
#!/usr/bin/env python print """ <html> <head> <style type="text/css"> tr:nth-child(even) { background-color: #f2f2f2; } td { padding: 5px; margin: 0; } </style> </head> <body> <table class="docutils"> <colgroup> <col width="12%" /> <col width="57%" /> <col width="31%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Ch</th> <th class="head">Description</th> <th class="head">Example output</th> </tr> </thead> <tbody valign="top"> <tr><td>a</td> <td><span>'a.m.'</span> or <span>'p.m.'</span> (Note that this is slightly different than PHP's output, because this includes periods to match Associated Press style.)</td> <td><span>'a.m.'</span></td> </tr> <tr><td>A</td> <td><span>'AM'</span> or <span>'PM'</span>.</td> <td><span>'AM'</span></td> </tr> <tr><td>b</td> <td>Month, textual, 3 letters, lowercase.</td> <td><span>'jan'</span></td> </tr> <tr><td>B</td> <td>Not implemented.</td> <td> </td> </tr> <tr><td>c</td> <td>ISO 8601 Format.</td> <td><span>2008-01-02</span> <span>10:30:00.000123</span></td> </tr> <tr><td>d</td> <td>Day of the month, 2 digits with leading zeros.</td> <td><span>'01'</span> to <span>'31'</span></td> </tr> <tr><td>D</td> <td>Day of the week, textual, 3 letters.</td> <td><span>'Fri'</span></td> </tr> <tr><td>f</td> <td>Time, in 12-hour hours and minutes, with minutes left off if they're zero. Proprietary extension.</td> <td><span>'1'</span>, <span>'1:30'</span></td> </tr> <tr><td>F</td> <td>Month, textual, long.</td> <td><span>'January'</span></td> </tr> <tr><td>g</td> <td>Hour, 12-hour format without leading zeros.</td> <td><span>'1'</span> to <span>'12'</span></td> </tr> <tr><td>G</td> <td>Hour, 24-hour format without leading zeros.</td> <td><span>'0'</span> to <span>'23'</span></td> </tr> <tr><td>h</td> <td>Hour, 12-hour format.</td> <td><span>'01'</span> to <span>'12'</span></td> </tr> <tr><td>H</td> <td>Hour, 24-hour format.</td> <td><span>'00'</span> to <span>'23'</span></td> </tr> <tr><td>i</td> <td>Minutes.</td> <td><span>'00'</span> to <span>'59'</span></td> </tr> <tr><td>I</td> <td>Not implemented.</td> <td> </td> </tr> <tr><td>j</td> <td>Day of the month without leading zeros.</td> <td><span>'1'</span> to <span>'31'</span></td> </tr> <tr><td>l</td> <td>Day of the week, textual, long.</td> <td><span>'Friday'</span></td> </tr> <tr><td>L</td> <td>Boolean for whether it's a leap year.</td> <td><span>True</span> or <span>False</span></td> </tr> <tr><td>m</td> <td>Month, 2 digits with leading zeros.</td> <td><span>'01'</span> to <span>'12'</span></td> </tr> <tr><td>M</td> <td>Month, textual, 3 letters.</td> <td><span>'Jan'</span></td> </tr> <tr><td>n</td> <td>Month without leading zeros.</td> <td><span>'1'</span> to <span>'12'</span></td> </tr> <tr><td>N</td> <td>Month abbreviation in Associated Press style. Proprietary extension.</td> <td><span>'Jan.'</span>, <span>'Feb.'</span>, <span>'March'</span>, <span>'May'</span></td> </tr> <tr><td>O</td> <td>Difference to Greenwich time in hours.</td> <td><span>'+0200'</span></td> </tr> <tr><td>P</td> <td>Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the special-case strings 'midnight' and 'noon' if appropriate. Proprietary extension.</td> <td><span>'1</span> <span>a.m.'</span>, <span>'1:30</span> <span>p.m.'</span>, <span>'midnight'</span>, <span>'noon'</span>, <span>'12:30</span> <span>p.m.'</span></td> </tr> <tr><td>r</td> <td>RFC 2822 formatted date.</td> <td><span>'Thu,</span> <span>21</span> <span>Dec</span> <span>2000</span> <span>16:01:07</span> <span>+0200'</span></td> </tr> <tr><td>s</td> <td>Seconds, 2 digits with leading zeros.</td> <td><span>'00'</span> to <span>'59'</span></td> </tr> <tr><td>S</td> <td>English ordinal suffix for day of the month, 2 characters.</td> <td><span>'st'</span>, <span>'nd'</span>, <span>'rd'</span> or <span>'th'</span></td> </tr> <tr><td>t</td> <td>Number of days in the given month.</td> <td><span>28</span> to <span>31</span></td> </tr> <tr><td>T</td> <td>Time zone of this machine.</td> <td><span>'EST'</span>, <span>'MDT'</span></td> </tr> <tr><td>u</td> <td>Microseconds.</td> <td><span>0</span> to <span>999999</span></td> </tr> <tr><td>U</td> <td>Seconds since the Unix Epoch (January 1 1970 00:00:00 UTC).</td> <td> </td> </tr> <tr><td>w</td> <td>Day of the week, digits without leading zeros.</td> <td><span>'0'</span> (Sunday) to <span>'6'</span> (Saturday)</td> </tr> <tr><td>W</td> <td>ISO-8601 week number of year, with weeks starting on Monday.</td> <td><span>1</span>, <span>53</span></td> </tr> <tr><td>y</td> <td>Year, 2 digits.</td> <td><span>'99'</span></td> </tr> <tr><td>Y</td> <td>Year, 4 digits.</td> <td><span>'1999'</span></td> </tr> <tr><td>z</td> <td>Day of the year.</td> <td><span>0</span> to <span>365</span></td> </tr> <tr><td>Z</td> <td>Time zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.</td> <td><span>-43200</span> to <span>43200</span></td> </tr> </tbody> </table> </body> </html> """
-
∞ QrCodeExample
from pygooglechart import QRChart # Create a 125x125 QR code chart chart = QRChart(125, 125) # Add the text chart.add_data('Hello, World!') # "Level H" error correction with a 0 pixel margin chart.set_ec('H', 0) # Download chart.download('qr-hello.png')
-
∞ A quick way to add ordinal suffixes to any number
def foo(n): str(n) + {1: 'st', 2: 'nd', 3: 'rd'}.get(4 if 10 <= n % 100 < 20 else n % 10, "th")
-
∞ short to byte array
def shortToByteArray(x): return (((x >> 8) & 0xFF), (x & 0xFF)) def byteArrayToShort(arr): return ( arr[0] << 8 ) + arr[1]
-
∞ prime factors
import math,sys s= set((2,)) l = [2] def isprime(n): if n in s:return True maxn = int(math.sqrt(n)) for i in l: if i>maxn: break if n%i == 0 : return False l.append(n) s.add(n) return True def getprimes(max=sys.maxint - 2): yield 2 i = 3 while i<max: if isprime(i):yield i i+=2 def decompose(n): max = int(math.sqrt(n)) res = [] div = False for i in getprimes(max): if i>max:break while n%i==0: n=n/i res.append(i) div = True if div: div=False max = int(math.sqrt(n)) if n>1:res.append(n) return res
-
∞ Paste to paste2.org
""" Posts a file to paste2.org. Can post multiple files at once. paste2.py [options] [files] -h, --help : Print this help -l, --lang : Specify the language for the paste -p, --parent : Sprecify parent paste """ import urllib import urllib2 import sys import getopt DEFAULT_LANG = 'python' PASTE2_URL = 'http://paste2.org/new-paste' def post_to_paste2(code, lang=DEFAULT_LANG, parent=0): """ Post to paste2, return url of new paste """ url = PASTE2_URL values = { 'lang': lang, 'description': '', 'code': code, 'parent': 0, } data = urllib.urlencode(values) req = urllib2.Request(url, data) paste_url = urllib2.urlopen(req).geturl() return paste_url def usage(): print "paste2.py [options] [files]" print " -h, --help : Print this help" print " -l, --lang : Specify the language for the paste" print " -p, --parent : Sprecify parent paste" def main(): try: opts, args = getopt.gnu_getopt(sys.argv[1:], "hl:p:v", ["help", "lang=", "parent="]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) lang = DEFAULT_LANG parent = None for o, a in opts: if o in ("-l", "--lang"): language = a elif o in ("-p", "--parent"): parent = a elif o in ("-h", "--help"): usage() sys.exit() else: assert False, "unhandled option" #loop through all files passed for file_name in args: file = open(file_name, 'r') paste_url = post_to_paste2(file.read(), lang=lang, parent=parent) print "%s -> %s" % (file_name, paste_url) if __name__ == "__main__": main()
-
∞ Get PYTHONPATH content, from bash shell
# Get PYTHONPATH content, from bash shell printf "import sys\nprint sys.path\nquit()\n" | python
-
∞ Regex for static tag replacement.
re.sub("<p>\s*? \s*?</p>", "REPLACEMENT", string)
-
∞ tag sanitizer
from BeautifulSoup import BeautifulSoup def sanitize_html(value): valid_tags = 'p i strong b u a h1 h2 h3 pre br'.split() valid_attrs = 'href src alt title'.split() soup = BeautifulSoup(value) for comment in soup.findAll( text=lambda text: isinstance(text, Comment)): comment.extract() for tag in soup.findAll(True): if tag.name not in valid_tags: tag.hidden = True tag.attrs = [(attr, val) for attr, val in tag.attrs if attr in valid_attrs] return soup.renderContents().decode('utf8').replace('javascript:', '')
-
∞ check ip is valid
def ipFormatChk(ip_str): """ Check IP is valid """ if len(ip_str.split()) == 1: ipList = ip_str.split('.') if len(ipList) == 4: for i, item in enumerate(ipList): try: ipList[i] = int(item) except: return False if not isinstance(ipList[i], int): return False if max(ipList) < 256: return True else: return False else: return False else: return False print ipFormatChk("unknown, 58.240 ")
-
∞ Prune empty directories in directory tree.
#!/usr/bin/env python # Copyright (c) 2005 Marc Butler. # # +desciption # Search for and delete empty directories. If deleting # an empty directory 'empties' it's parent dir. The parent # dir will also be deleted. # -desc import re import os import sys import shutil def FindEmptyDirs (dirlist, dirname, filenames): if filenames == []: dirlist.append(dirname) def IsEmpty (dir): return os.listdir(dir) == [] def UnwindingDelete (emptydir): if not os.path.isdir(emptydir): return if not IsEmpty(emptydir): return os.rmdir(emptydir) UnwindingDelete(os.path.split(emptydir)[0]) def Usage (): print """ Usage: prunedirs.py dir Remove all empty directories under dir. """ if __name__ == '__main__': if len(sys.argv) != 2: Usage() sys.exit(1) leaves = [] os.path.walk(sys.argv[1], FindEmptyDirs, leaves) print 'Found %d leaf empty dirs.' % (len(leaves)) for d in leaves: UnwindingDelete(d)
-
∞ List targets in a makefile
# Copyright (c) 2006 Marc Butler. All Rights Reserved. # License: Public Domain. # # List Targets # List top-level targets in a makefile. from __future__ import with_statement import re import sys # Default to Makefile in current dir if no build files # are specified on the command line. makefile = 'Makefile' if len(sys.argv) > 1: makefile = sys.argv[1] with open(makefile, 'r') as f: for line in f: m = re.match('^([^:#]+):', line) if m: print m.group(0)
-
∞ Generate makefile for current directory.
#!/usr/bin/env python import os import sys import glob import re def die(msg): print msg sys.exit(1) def is_known_ext(fname): known_exts = [ r"\.c$", r"\.cpp$", r"\.cc$", r"\.cxx$", r"\.C$" ] for pat in known_exts: # Don't use re.match as it wants the *entire* string to match # which doesn't work with the partial regexes above. if re.search(pat, fname): return True return False # Do not overwrite Makefile if it already exists. if os.path.exists("Makefile"): die("Makefile already exists!") # Gather up a list of all source files. src = [] for f in glob.glob("*"): if is_known_ext(f): src.append(f) if len(src) == 0: die("No recognizable source files!")
-
∞ Delete all user playlists in iTunes using python and COM (windows).
# Copyright (c) 2007 Marc Butler. # Delete all user playlists in iTunes for Windows using the COM # interface. import sys import win32com.client # These playlists are generated and maintained by iTunes (version 7, Windows). # So do not touch them when deleting playlists. I think the user *can* delete # them but this script should follow the law of least suprise. iTunesGeneratedPlaylists = [ u'Purchased', u'Party Shuffle', u'90\u2019s Music', u'Music Videos', u'My Top Rated', u'Recently Added', u'Recently Played', u'Top 25 Most Played' ] app = win32com.client.Dispatch("iTunes.Application") lib = app.LibrarySource playlists = lib.Playlists plcount = playlists.Count curr = 1 while curr < plcount: p = playlists.Item(curr) if not p.Name in iTunesGeneratedPlaylists and p.Kind == 2: print 'Deleting playlist: %s' % (p.Name.encode('utf-8')) # Catch error here? p.Delete curr += 1
-
∞ Relative path from A to B
# Note: Python 2.6+ has os.path.relpath, no need for this. def base_path_relative(src, dest=None): """ Return a relative path from src to dest(default=cwd). >>> base_path_relative("/usr/bin", "/tmp/foo/bar") ../../tmp/foo/bar >>> base_path_relative("/usr/bin", "/usr/lib") ../lib >>> base_path_relative("/tmp", "/tmp/foo/bar") foo/bar """ from os import getcwd, sep from os.path import abspath if dest is None: dest = getcwd() srclist = abspath(src).split(sep) destlist = abspath(dest).split(sep) loc = [spath == dpath for spath, dpath in zip(srclist, destlist)].index(False) rellist = ([ ".." ] * (len(srclist) - loc)) + destlist[loc:] return sep.join(rellist)
-
∞ python for loop with step
#!/usr/bin/env python # -*- encoding: utf8 -*- import os, sys, MySQLdb # --------------------------------------------------------------------------------------------- def getConn(): try: conn = MySQLdb.connect(host='192.168.200.254', user='root', passwd='', db='test', port=3306, charset='utf8') return conn except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) # --------------------------------------------------------------------------------- def closeConn(conn): conn.close() #---------------------------------------------------------------------- def updatePage(conn, startID, endID): cursor = conn.cursor() cursor.execute("update jute.jute_user set topicsPerPage = 35 where topicsPerPage < 35 and id between " + str(startID) + " and " + str(endID)) conn.commit() if __name__ == '__main__': conn = getConn() for i in range(10000, 2000000, 10000): print "Processing " + str(i-9999) + " - " + str(i) + ":" # updatePage(conn, (i-9999), i) conn.close()
-
∞ python currying
def addFactory(x): def add(y): return x+y return add add5 = addFactory(5) y = add5(4) print(y)



Learning Python, 3rd Edition