Commit 50df227b by O'Reilly Media, Inc.

Initial commit

parents

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

9780596007973
\ No newline at end of file
## Example files for the title:
# Python Cookbook 2nd Edition, by David Ascher
[![Python Cookbook 2nd Edition, by David Ascher](http://akamaicovers.oreilly.com/images/9780596007973/cat.gif)](https://www.safaribooksonline.com/library/view/title/0596007973//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
#!/usr/bin/python
import time, sys, os, email
now = time.time()
# get archive of previously-seen message-ids and times
kde_dir = os.expanduser('~/.kde')
if not os.path.isdir(kde_dir):
os.mkdir(kde_dir)
arfile = os.path.join(kde_dir, 'duplicate_mails')
duplicates = {}
try:
archive = open(arfile)
except IOError:
pass
else:
for line in archive:
when, msgid = line[:-1].split(' ', 1)
duplicates[msgid] = float(when)
archive.close()
redo_archive = False
# suck message in from stdin and study it
msg = email.message_from_file(sys.stdin)
msgid = msg['Message-ID']
if msgid:
if msgid in duplicates:
# duplicate message: alter its subject
subject = msg['Subject']
if subject is None:
msg['Subject'] = '**** DUP **** ' + msgid
else:
del msg['Subject']
msg['Subject'] = '**** DUP **** ' + subject
else:
# non-duplicate message: redo the archive file
redo_archive = True
duplicates[msgid] = now
else:
# invalid (missing message-id) message: alter its subject
subject = msg['Subject']
if subject is None:
msg['Subject'] = '**** NID **** '
else:
del msg['Subject']
msg['Subject'] = '**** NID **** ' + subject
# emit message back to stdout
print msg
if redo_archive:
# redo archive file, keep only msgs from the last two hours
keep_last = now - 2*60*60.0
archive = file(arfile, 'w')
for msgid, when in duplicates.iteritems():
if when > keep_last:
archive.write('%9.2f %s\n' % (when, what))
archive.close()
import winsound
try:
winsound.PlaySound("*", winsound.SND_ALIAS)
except RuntimeError, e:
print 'Sound system has problems,', e
else:
print 'Sound system is OK'
from ctypes import windll
dll = windll[r'C:\Path\To\Some.DLL']
result = dll.DllRegisterServer()
result = dll.DllUnregisterServer()
from ctypes import oledll
dll = oledll[r'C:\Path\To\Some.DLL']
dll.DllRegisterServer()
dll.DllUnregisterServer()
import _winreg as wr
aReg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE)
targ = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
aKey = wr.OpenKey(aReg, targ, 0, wr.KEY_WRITE)
wr.DeleteValue(aKey, "MyNewKey")
wr.CloseKey(aKey)
wr.CloseKey(aReg)
import _winreg as wr
aReg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE)
try:
targ = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
print "*** Reading from", targ, "***"
aKey = wr.OpenKey(aReg, targ)
try:
for i in xrange(1024):
try:
n, v, t = wr.EnumValue(aKey, i)
print i, n, v, t
except EnvironmentError:
print "You have", i, "tasks starting at logon"
break
finally:
wr.CloseKey(aKey)
print "*** Writing to", targ, "***"
aKey = wr.OpenKey(aReg, targ, 0, wr.KEY_WRITE)
try:
try:
wr.SetValueEx(aKey, "MyNewKey", 0, REG_SZ, r"c:\winnt\explorer.exe")
except EnvironmentError:
print "Encountered problems writing into the Registry..."
raise
finally:
CloseKey(aKey)
finally:
CloseKey(aReg)
import win32net
import win32netcon
shinfo={}
shinfo['netname'] = 'python test'
shinfo['type'] = win32netcon.STYPE_DISKTREE
shinfo['remark'] = 'data files'
shinfo['permissions'] = 0
shinfo['max_uses'] = -1
shinfo['current_uses'] = 0
shinfo['path'] = 'c:\\my_data'
shinfo['passwd'] = ''
server = 'servername'
win32net.NetShareAdd(server, 2, shinfo)
from win32gui import GetClassName
if GetClassName(shellwindow.HWND) == 'IEFrame':
## ...
while shellwindow.Busy:
time.sleep(0.2)
from win32com.client import Dispatch
ShellWindowsCLSID = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
ShellWindows = Dispatch(ShellWindowsCLSID)
print '%d instances of IE' % len(shellwindows)
print
for shellwindow in ShellWindows :
print shellwindow
print shellwindos.LocationName
print shellwindos.LocationURL
print
contact = ofContacts.Items.Item(oc + 1)
from win32com.client import gencache, constants
DEBUG = False
class MSOutlook(object):
def __init__(self):
try:
self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application")
self.outlookFound = True
except:
print "MSOutlook: unable to load Outlook"
self.outlookFound = False
self.records = []
def loadContacts(self, keys=None):
if not self.outlookFound: return
onMAPI = self.oOutlookApp.GetNamespace("MAPI")
ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts)
if DEBUG: print "number of contacts:", len(ofContacts.Items)
for oc in range(len(ofContacts.Items)):
contact = ofContacts.Items.Item(oc + 1)
if contact.Class == constants.olContact:
if keys is None:
# no keys were specified, so build up a list of all keys
# that belong to some types we know we can deal with
good_types = int, str, unicode
keys = [key for key in contact._prop_map_get_
if isinstance(getattr(contact, key), good_types) ]
if DEBUG:
print "Fields\n=================================="
keys.sort()
for key in keys: print key
record = {}
for key in keys:
record[key] = getattr(contact, key)
self.records.append(record)
if DEBUG:
print oc, contact.FullName
if __name__ == '__main__':
if '-d' in sys.argv:
DEBUG = True
if DEBUG:
print "attempting to load Outlook"
oOutlook = MSOutlook()
if not oOutlook.outlookFound:
print "Outlook not found"
sys.exit(1)
fields = ['FullName', 'CompanyName',
'MailingAddressStreet', 'MailingAddressCity',
'MailingAddressState', 'MailingAddressPostalCode',
'HomeTelephoneNumber', 'BusinessTelephoneNumber',
'MobileTelephoneNumber', 'Email1Address', 'Body',
]
if DEBUG:
import time
print "loading records..."
startTime = time.time()
# to get all fields just call oOutlook.loadContacts()
# but getting a specific set of fields is much faster
oOutlook.loadContacts(fields)
if DEBUG:
print "loading took %f seconds" % (time.time() - startTime)
print "Number of contacts: %d" % len(oOutlook.records)
print "Contact: %s" % oOutlook.records[0]['FullName']
print "Body:\n%s" % oOutlook.records[0]['Body']
cpu_type: PowerPC G4 (3.3)
current_processor_speed: 800 MHz
l2_cache_size: 256 KB
physical_memory: 640 MB
user_name: Alex (alex)
os_version: Mac OS X 10.3.6 (7R28)
ip_address: [u'192.168.0.190']
#!/usr/bin/env python
from xml import dom
from xml.dom.xmlbuilder import DOMInputSource, DOMBuilder
import datetime, time, os
def group(seq, n):
"""group([0, 3, 4, 10, 2, 3, 1], 3) => [(0, 3, 4), (10, 2, 3)]
Group a sequence into n-subseqs, discarding incomplete subseqs.
"""
return [ seq[i:i+n] for i in xrange(0, len(seq)-n+1, n) ]
def remove_whitespace_nodes(node):
"""Removes all of the whitespace-only text descendants of a DOM node."""
remove_list = []
for child in node.childNodes:
if child.nodeType == dom.Node.TEXT_NODE and not child.data.strip():
remove_list.append(child)
elif child.hasChildNodes():
remove_whitespace_nodes(child)
for child in remove_list:
node.removeChild(child)
child.unlink()
class POpenInputSource(DOMInputSource):
"Use stdout from an external program as a DOMInputSource"
def __init__(self, command):