Skip to content Skip to main navigation Skip to footer

# python

## Python实现高效求解素数的方法

Python实现高效求解素数的方法是如何来实现的呢？下面的内容将会通过具体的实例来演示Python实现高效求解素数的方法的实现方法及相关技巧：

#coding:utf-8 #设置python文件的编码为utf-8，这样就可以写入中文注释
def primeRange(n):
myArray=[1 for x in range(n+1)] ##列表解析，生成长度为(n+1)的列表，每个数值都为1
myArray[0]=0
myArray[1]=0
startPos=2
while startPos <= n: if myArray[startPos]==1: key=2 resultPos = startPos * key #可知startPos的整数倍都不是素数，设置startPos的整数倍的位置为0表示非素数 while resultPos <= n: myArray[resultPos] =0 key += 1 resultPos = startPos *key startPos += 1 resultList=[] ##将最终的素数保存在resultList列表返回 startPos=0 while startPos <= n: if myArray[startPos] == 1: resultList.append(startPos) startPos += 1 return resultList numString=raw_input("Input the Range(>3):”)
numInt=int(numString)
if numInt <= 3: print "The Number Need to be greater than 3" else: primeResult=primeRange(numInt) print "The Result is:",primeResult [/code]
Python实现高效求解素数的方法就是这样，欢迎大家参考。。。。

## python实现文件快照加密保护的方法

python实现文件快照加密保护的方法是如何来实现的呢？下面的内容将会通过具体的实例来演示python实现文件快照加密保护的方法的实现方法及相关技巧：

```# Hello, this is a script written in Python. See http://www.pyhon.org
#
# Snapper 1.2p
#
# This script will walk a directory (and its subdirectories) and compute
# SHA (Secure Hash Algorithm) for specific files (according to their
# extensions) and ouput a CSV file (suited for loading into a spreadsheet
# editor,a database or simply comparing with diff or ExamDiff.).
#
# You can redirect the output of this script to a file.
# eg. python snapper.py > todayCheck.csv
#
# This script can be usefull to check system files tampering.
#
# This script is public domain. Feel free to reuse it.
# The author is:
#    Sebastien SAUVAGE
#    <sebsauvage at sebsauvage dot net>
#    http://sebsauvage.net
#
# More quick & dirty scripts are available at http://sebsauvage.net/python/
#
# Directory to scan and extensions are hardcoded below:
directoryStart = r'c:windows'
extensionList=['.exe','.dll','.ini','.ocx','.cpl','.vxd','.drv','.vbx','.com','.bat','.src',
'.sys','.386','.acm','.ax', '.bpl','.bin','.cab','.olb','.mpd','.pdr','.jar']
import os,string,sha,stat,sys
def snapper ( directoryStart , extensionList ) :
os.path.walk( directoryStart, snapper_callback, extensionList )
def snapper_callback ( extensionList , directory, files ) :
sys.stderr.write('Scanning '+directory+'n')
for fileName in files:
if os.path.isfile( os.path.join(directory,fileName) ) :
if string.lower(os.path.splitext(fileName)[1]) in extensionList :
filelist.append(fileSHA ( os.path.join(directory,fileName) ))
def fileSHA ( filepath ) :
sys.stderr.write(' Reading '+os.path.split(filepath)[1]+'n')
file = open(filepath,'rb')
digest = sha.new()
data = file.read(65536)
while len(data) != 0:
digest.update(data)
data = file.read(65536)
file.close()
return '"'+filepath+'",'+str(os.stat(filepath)[6])+',"'+digest.hexdigest()+'"'
sys.stderr.write('Snapper 1.1p - http://sebsauvage.net/python/n')
filelist = []
snapper( directoryStart , extensionList )
sys.stderr.write('Sorting...n')
filelist.sort()
filelist.insert(0, '"File path","File size","SHA"' )
sys.stderr.write('Printing...n')
for line in filelist:
print line
sys.stderr.write('All done.n')
```

python实现文件快照加密保护的方法就是这样，欢迎大家参考。。。。

## Python中的序列化与反序列化的使用介绍

Python中的序列化与反序列化是如何来使用的呢？下面的内容将会通过具体的实例来演示Python中的序列化与反序列化的使用方法及相关技巧：

cPickle模块是使用C语言实现的，所以在运行效率上比pickle要高。但是cPickle模块中定义的类型不能被继承（其实大多数时候，我们不需要从这些类型中继承。）。cPickle和pickle的序列化/反序列化规则是一样的，我们可以使用pickle序列化一个对象，然后使用cPickle来反序列化。同时，这两个模块在处理自引用类型时会变得更加“聪明”，它不会无限制的递归序列化自引用对象，对于同一对象的多次引用，它只会序列化一次。例如：

```import marshal, pickle
list = [1]
list.append(list)
byt1 = marshal.dumps(list)
#出错, 无限制的递归序列化
byt2 = pickle.dumps(list)
#No problem
<strong>pickle的序列化规则
</strong> ```

Python规范（Python-specific）提供了pickle的序列化规则。这就不必担心不同版本的Python之间序列化兼容性问题。默认情况下，pickle的序列化是基于文本的，我们可以直接用文本编辑器查看序列化的文本。我们也可以序列成二进制格式的数据，这样的结果体积会更小。更详细的内容，可以参考Python手册pickle模块。

pickle.dump(obj, file[, protocol])

pickle.load(file)

```#coding=gbk
import pickle, StringIO
class Person(object):
'''自定义类型。
'''
def __init__(self, name, address):
self.name = name
self.address = address
def display(self):
print 'name:', self.name, 'address:', self.address
jj = Person("JGood", "中国 杭州")
jj.display()
file = StringIO.StringIO()
pickle.dump(jj, file, 0)
#序列化
#print file.getvalue() #打印序列化后的结果
#del Person #反序列的时候，必须能找到对应类的定义。否则反序列化操作失败。
file.seek(0)
jj1 = pickle.load(file)
#反序列化
jj1.display()
file.close()
```

pickle.dumps(obj[, protocol])
pickle.loads(string)

python模块中还定义了两个类，分别用来序列化、反序列化对象。
class pickle.Pickler(file[, protocal]):

dump(obj):

clear_memo()

```#coding=gbk
import pickle, StringIO
class Person(object):
'''自定义类型。
'''
def __init__(self, name, address):
self.name = name
self.address = address
def display(self):
print 'name:', self.name, 'address:', self.address
fle = StringIO.StringIO()
pick = pickle.Pickler(fle)
person = Person("JGood", "Hangzhou China")
pick.dump(person)
val1 = fle.getvalue()
print len(val1)
pick.clear_memo()
#注释此句，再看看运行结果
pick.dump(person)
#对同一引用对象再次进行序列化
val2 = fle.getvalue()
print len(val2)
#---- 结果 ----
#148
#296
#
#将这行代码注释掉：pick.clear_memo()
#结果为：
#148
#152
class pickle.Unpickler(file):
```

load():

```#.... 接上个例子中的代码
fle.seek(0)
unpick = pickle.Unpickler(fle)
print unpick.load()
```

```class A(object):
class B(object):
def __init__(self, name):
self.name = name
def __init__(self):
print 'init A'
b = A.B("my name")
print b
c = pickle.dumps(b, 0)
#失败哦
print pickle.loads(c)
```

Python中的序列化与反序列化就是这样，欢迎大家参考。。。。

## RC4文件加密的python实现方法

RC4文件加密的python实现方法是如何来实现的呢？下面的内容将会通过具体的实例来演示RC4文件加密的python实现方法的实现方法及相关技巧：

```# for python 3.0
# from 李勃
import struct,sys,os,binascii
"""
RC4加密算法
16*16 S盒
加密单元:short
"""
def RC4(pkey,keylen,pin,dlen):
N=65536
S = list(range(N))
j = 0
for i in range(N):
j = (j + S[i] + pkey[i%keylen])%N
temp = S[i]
S[i] = S[j]
S[j] = temp
i = j = 0
pout= b''
for x in range(dlen):
i = i+1
j = (j + S[i])%N
temp = S[i]
S[i] = S[j]
S[j] = temp
pout += struct.pack('H',pin[x]^S[(S[i]+S[j])%N])
return(pout)
# bytes->short
def Coding(data):
if(len(data)%2):
data+=b''
dlen = len(data)//2
return(struct.unpack(str(dlen)+'H',data))
# short->bytes
def unCoding(data):
d=b''
for i in range(len(data)):
d += struct.pack('H',data[i])
return(d)
#产生32字节密钥
def CreatKey(Keyt):
pl = len(Keyt)
Key=b''
r=0
for i in range(32):
k=(Keyt[r%pl]+i)%256
Key+= struct.pack('B',k)
r+=1
return Key
#更新密钥
def UpdataKey(Keyt):
Key = unCoding(Keyt)
#循环左移
Key = Key[1:] + struct.pack('B',Key[0])
tem=0
#求和
for i in range(len(Key)):
tem += Key[i];
Keyo=b''
#Xor
for i in range(len(Key)):
Keyo += struct.pack('B',(Key[i]^tem)%256)
tem += Keyo[i]>>3
tem = tem % 256
return(Coding(Keyo))
if __name__ == '__main__':
#获得输入文件
if len(sys.argv)==1:
filename = input('源文件: ')
else:
filename = sys.argv[1]
try:
fin = open(filename,'rb')
except:
print('打开文件失败！')
input()
sys.exit()
print(filename)
#打开输出文件
if filename[-4:]=='.RC4':
eID = 1
key=input('输入解密密钥: ').encode()
ofilename = filename[:-4]
else:
eID = 2
key=input('输入加密密钥: ').encode()
ofilename = filename+'.RC4'
key = Coding(CreatKey(key))
key = UpdataKey(key)
#处理重名
while os.path.exists(ofilename):
ofilename = os.path.dirname(ofilename)+ '\副本 '+ os.path.basename(ofilename)
fout = open(ofilename,'wb')
print(ofilename)
#解密
if eID==1:
#读文件长度
filelen = struct.unpack('I',fin.read(4))[0]
print('FlieLen =',filelen,'n......')
while 1:
#读块大小
ps= fin.read(2)
if not ps:
#文件结束
break
packsize = struct.unpack('H',ps)[0]
#读数据
dd=fin.read(packsize)
#解密
dd=Coding(dd)
x = RC4(key,len(key),dd,len(dd))
key = UpdataKey(key)
#crc
crc = struct.unpack('I',fin.read(4))[0]
if binascii.crc32(x)!=crc:
print('CRC32校验错误！',crc,binascii.crc32(x))
input()
sys.exit()
fout.write(x)
#裁剪末尾填充位
fout.truncate(filelen)
#加密
elif eID==2:
#获得文件长度
fin.seek(0,2)
filelen = fin.tell()
print('FlieLen =',filelen,'n......')
fin.seek(0,0)
fout.write(struct.pack('I',filelen))
while 1:
#读数据
dd=fin.read(65534)
if not dd:
#文件结束
break
#末尾填充
srl = len(dd)
if srl%2:
srl+=1;
dd+=b''
#crc
crc = struct.pack('I',binascii.crc32(dd))
#加密数据
dd=Coding(dd)
x = RC4(key,len(key),dd,len(dd))
key = UpdataKey(key)
#写入文件
fout.write(struct.pack('H',srl))
fout.write(x)
fout.write(crc)
fin.close()
fout.close()
print('OK!')
input()
```

RC4文件加密的python实现方法就是这样，欢迎大家参考。。。。

## python清除指定目录内所有文件中script的方法

python清除指定目录内所有文件是如何来实现的呢？下面的内容将会通过具体的实例来演示python清除指定目录内所有文件的实现方法及相关技巧：

```# Hello, this is a script written in Python. See http://www.pyhon.org
import os,sys,string,re
message = """
stripscripts 1.1p - Script stripper
This script will walk a directory (and its subdirectories) and disable
all scripts (javascript, vbscript...) from .html and .htm files.
(The scripts will not be deleted, but simply deactivated, so that
you can review them if you like.)
Can be usefull for sites you have downloaded with HTTrack or similar tools.
No more nosey or buggy scripts in your local html files.
Syntax : python %s <directory>
Example : python %s d:myfiles
This script is public domain. You can freely reuse it.
The author is
Sebastien SAUVAGE
<sebsauvage at sebsauvage dot net>
http://sebsauvage.net
More quick & dirty scripts are available at http://sebsauvage.net/python/
""" % ((sys.argv[0], )*2)
def stripscripts ( directoryStart ) :
os.path.walk( directoryStart, callback, '' )
def callback ( args, directory, files ) :
print 'Scanning',directory
for fileName in files:
if os.path.isfile( os.path.join(directory,fileName) ) :
if string.lower(os.path.splitext(fileName)[1]) in ['.html','.htm'] :
stripScriptFromHtml ( os.path.join(directory,fileName) )
def stripScriptFromHtml ( filepath ) :
print ' Processing',os.path.split(filepath)[1]
file = open(filepath, 'rb')
html = file.read()
file.close()
regexp = re.compile(r'<script.*&#63;>', re.IGNORECASE)
html = regexp.sub('<script language="MonthyPythonsScript">',html)
file = open(filepath, 'w+')
file.write(html)
file.close()
if len(sys.argv) > 1 :
stripscripts( sys.argv[1] )
else:
print message
```

python清除指定目录内所有文件就是这样，欢迎大家参考。。。。

## python读写ini配置文件方法实例分析

python读写ini配置文件方法是如何来实现的呢？下面的内容将会通过具体的实例来演示python读写ini配置文件方法的实现方法及相关技巧：

```import ConfigParser
import os
class ReadWriteConfFile:
currentDir=os.path.dirname(__file__)
filepath=currentDir+os.path.sep+"inetMsgConfigure.ini"
@staticmethod
def getConfigParser():
cf=ConfigParser.ConfigParser()
cf.read(ReadWriteConfFile.filepath)
return cf
@staticmethod
def writeConfigParser(cf):
f=open(ReadWriteConfFile.filepath,"w");
cf.write(f)
f.close();
@staticmethod
def getSectionValue(section,key):
cf=ReadWriteConfFile.getConfigParser()
return cf.get(section, key)
@staticmethod
def addSection(section):
cf=ReadWriteConfFile.getConfigParser()
allSections=cf.sections()
if section in allSections:
return
else:
cf.add_section(section)
ReadWriteConfFile.writeConfigParser(cf)
@staticmethod
def setSectionValue(section,key,value):
cf=ReadWriteConfFile.getConfigParser()
cf.set(section, key, value)
ReadWriteConfFile.writeConfigParser(cf)
if __name__ == '__main__':
ReadWriteConfFile.addSection( 'messages')
ReadWriteConfFile.setSectionValue( 'messages','name','sophia')
x=ReadWriteConfFile.getSectionValue( 'messages','1000')
print x
```

python读写ini配置文件方法就是这样，欢迎大家参考。。。。

## python获得文件创建时间和修改时间的方法

python获得文件创建时间和修改时间是如何来实现的呢？下面的内容将会通过具体的实例来演示python获得文件创建时间和修改时间的实现方法及相关技巧：

import os.path, time
import exceptions
class TypeError (Exception):
pass
if __name__ == ‘__main__’:
if (len(os.sys.argv) < 1): raise TypeError() else: print "os.sys.argv[0]: %s" % os.sys.argv[0] # os.sys.argv[0] is the current file, in this case, file_ctime.py f = os.sys.argv[0] mtime = time.ctime(os.path.getmtime(f)) ctime = time.ctime(os.path.getctime(f)) print "Last modified : %s, last created time: %s" % (mtime, ctime) [/code]
python获得文件创建时间和修改时间就是这样，欢迎大家参考。。。。

## python过滤字符串中不属于指定集合中字符的类

python过滤字符串中不属于指定集合中字符是如何来实现的呢？下面的内容将会通过具体的实例来演示python过滤字符串中不属于指定集合中字符的实现方法及相关技巧：

```# -*- coding: utf-8 -*-
import sets
class Keeper(object):
def __init__(self, keep):
self.keep = sets.Set(map(ord, keep))
def __getitem__(self, n):
if n not in self.keep:
return None
return unichr(n)
def __call__(self, s):
return s.translate(self)
makefilter = Keeper
if __name__ == '__main__':
just_vowels = makefilter('aeiouy')
print just_vowels(u'four score and seven years ago')
# 输出: ouoeaeeyeaao
print just_vowels(u'tiger, tiger burning bright')
# 输出: ieieuii
```

python过滤字符串中不属于指定集合中字符就是这样，欢迎大家参考。。。。

## python判断一个集合是否包含了另外一个集合中所有项的方法

python判断一个集合是否包含了另外一个集合中所有项是如何来实现的呢？下面的内容将会通过具体的实例来演示python判断一个集合是否包含了另外一个集合中所有项的实现方法及相关技巧：

```>>> L1 = [1, 2, 3, 3]
>>> L2 = [1, 2, 3, 4]
>>> set(L1).difference(L2)
set([ ])
>>> set(L2).difference(L1)
set([4])
```

python判断一个集合是否包含了另外一个集合中所有项就是这样，欢迎大家参考。。。。

## python检查序列seq是否含有aset中项的方法

python检查序列seq是否含有aset中项是如何来实现的呢？下面的内容将会通过具体的实例来演示python检查序列seq是否含有aset中项的实现方法及相关技巧：

```# -*- coding: utf-8 -*-
def containsAny(seq, aset):
""" 检查序列seq 是否含有aset 中的项 """
for c in seq:
if c in aset: return True
return False
seq = [1,2,3]
aset = [3,4,5]
print(containsAny(seq,aset))
```

python检查序列seq是否含有aset中项就是这样，欢迎大家参考。。。。

## python爬取淘宝商品的方法

python爬取淘宝商品是如何来实现的呢？下面的内容将会通过具体的实例来演示python爬取淘宝商品的实现方法及相关技巧：

```import time
import leveldb
from urllib.parse import quote_plus
import re
import json
import itertools
import sys
import requests
from queue import Queue
from threading import Thread
URL_BASE = 'http://s.m.taobao.com/search&#63;q={}&n;=200&m;=api4h5&style;=list&page;={}'
def url_get(url):
# print('GET ' + url)
header = dict()
header['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
header['Accept-Encoding'] = 'gzip,deflate,sdch'
header['Accept-Language'] = 'en-US,en;q=0.8'
header['Connection'] = 'keep-alive'
header['DNT'] = '1'
#header['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36'
header['User-Agent'] = 'Mozilla/12.0 (compatible; MSIE 8.0; Windows NT)'
return requests.get(url, timeout = 5, headers = header).text
def item_thread(cate_queue, db_cate, db_item):
while True:
try:
cate = cate_queue.get()
post_exist = True
try:
state = db_cate.Get(cate.encode('utf-8'))
if state != b'OK': post_exist = False
except:
post_exist = False
if post_exist == True:
print('cate-{}: {} already exists ... Ignore'.format(cate, title))
continue
db_cate.Put(cate.encode('utf-8'), b'crawling')
for item_page in itertools.count(1):
url = URL_BASE.format(quote_plus(cate), item_page)
for tr in range(5):
try:
items_obj = json.loads(url_get(url))
break
except KeyboardInterrupt:
quit()
except Exception as e:
if tr == 4: raise e
if len(items_obj['listItem']) == 0: break
for item in items_obj['listItem']:
item_obj = dict(
_id = int(item['itemNumId']),
name = item['name'],
price = float(item['price']),
query = cate,
category = int(item['category']) if item['category'] != '' else 0,
nick = item['nick'],
area = item['area'])
db_item.Put(str(item_obj['_id']).encode('utf-8'),
json.dumps(item_obj, ensure_ascii = False).encode('utf-8'))
print('Get {} items from {}: {}'.format(len(items_obj['listItem']), cate, item_page))
if 'nav' in items_obj:
for na in items_obj['nav']['navCatList']:
try:
db_cate.Get(na['name'].encode('utf-8'))
except:
db_cate.Put(na['name'].encode('utf-8'), b'waiting')
db_cate.Put(cate.encode('utf-8'), b'OK')
print(cate, 'OK')
except KeyboardInterrupt:
break
except Exception as e:
print('An {} exception occured'.format(e))
def cate_thread(cate_queue, db_cate):
while True:
try:
for key, value in db_cate.RangeIter():
if value != b'OK':
print('CateThread: put {} into queue'.format(key.decode('utf-8')))
cate_queue.put(key.decode('utf-8'))
time.sleep(10)
except KeyboardInterrupt:
break
except Exception as e:
print('CateThread: {}'.format(e))
if __name__ == '__main__':
db_cate = leveldb.LevelDB('./taobao-cate')
db_item = leveldb.LevelDB('./taobao-item')
orig_cate = '正装'
try:
db_cate.Get(orig_cate.encode('utf-8'))
except:
db_cate.Put(orig_cate.encode('utf-8'), b'waiting')
cate_queue = Queue(maxsize = 1000)
cate_th = Thread(target = cate_thread, args = (cate_queue, db_cate))
cate_th.start()
item_th = [Thread(target = item_thread, args = (cate_queue, db_cate, db_item)) for _ in range(5)]
for item_t in item_th:
item_t.start()
cate_th.join()
```

python爬取淘宝商品就是这样，欢迎大家参考。。。。

## Python如何监控程序的执行时间并将其写入日志

Python监控程序的执行时间并将其写入日志是如何来实现的呢？下面的内容将会通过具体的实例来演示Python监控程序的执行时间并将其写入日志的实现方法及相关技巧：

```# /usr/bin/python
# -*- coding:utf-8 -*-
from time import time
def logged(when):
def log(f,*args,**kargs):
print '''
called:
functions:%s
args: %r
kargs: %r
'''  % (f,args,kargs)
def pre_logged(f):
def wrapper(*args,**kargs):
log(f,*args,**kargs)
return f(*args,**kargs)
return wrapper
def post_logged(f):
def wrapper(*args,**kargs):
now = time()
try:
return f(*args,**kargs)
finally:
log(f,*args,**kargs)
print "time delta:%s" % (time()-now)
return wrapper
try:
return {"pre":pre_logged,"post":post_logged}[when]
except KeyError,e:
raise ValueError(e),'must be "pre" or "post"'
@logged("post")
def hello(name):
print "hello,",name
hello("world!")
'''

'''
```

Python监控程序的执行时间并将其写入日志就是这样，欢迎大家参考。。。。

## python的keyword模块用法介绍

python的keyword模块是如何来使用的呢？下面的内容将会通过具体的实例来演示python的keyword模块的使用方法及相关技巧：

```Help on module keyword:
NAME
keyword - Keywords (from "graminit.c")
FILE
/usr/lib64/python2.6/keyword.py
DESCRIPTION
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
FUNCTIONS
iskeyword = __contains__(...)
x.__contains__(y) <==> y in x.
DATA
__all__ = ['iskeyword', 'kwlist']
kwlist = ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', ...
```

```>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
```

```>>> keyword.iskeyword('and')
True
>>>
>>> keyword.iskeyword('has')
False
```

python的keyword模块就是这样，欢迎大家参考。。。。

## Python实现sqlAlchemy对象转换成dict的方法介绍

Python实现sqlAlchemy对象转换成dict的方法是如何来实现的呢？下面的内容将会通过具体的实例来演示Python实现sqlAlchemy对象转换成dict的方法的实现方法及相关技巧：

```p = session.query(Post).first()
p.__dict__
```

```Base = sqlalchemy.ext.declarative.declarative_base()
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
title = Column(String)
```

```def to_dict(self):
return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}
Base.to_dict = to_dict
```

```p = session.query(Post).first()
p.to_dict()
```

Python实现sqlAlchemy对象转换成dict的方法就是这样，欢迎大家参考。。。。

## Python的Django框架中TEMPLATES项的设置方法详细介绍

Python的Django框架中TEMPLATES项的设置是如何来实现的呢？下面的内容将会通过具体的实例来演示Python的Django框架中TEMPLATES项的设置的实现方法及相关技巧：

TEMPLATES

Django 1.8的新特性

```TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
},
]
```

BACKEND

```  'django.template.backends.django.DjangoTemplates'
'django.template.backends.jinja2.Jinja2'
```

NAME

DIRS

APP_DIRS

OPTIONS

TEMPLATE_CONTEXT_PROCESSORS

```("django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages")
```

• Django 1.8的变化：
• 在Django 1.8中，内建模板的上下文处理器从django.core.context_processors移至django.template.context_processors。

TEMPLATE_DEBUG

• 自1.8版本起，不赞成使用：
• 在一个DjangoTemplates引擎中的OPTIONS设置’debug’ 选项来代替。

TEMPLATE_DIRS

• 自1.8版本起，不赞成使用：
• 在一个DjangoTemplates引擎中设置’DIRS’选项来代替。

django.template.loaders.filesystem.Loader搜索模板源代码的路径列表，，按搜索顺序排列。

TEMPLATE_LOADERS

```('django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader')
```
• 自1.8版本起，不赞成使用：
• 在一个DjangoTemplates引擎中的OPTIONS设置’loader’选项来代替。

TEMPLATE_STRING_IF_INVALID

• 自1.8版本起，不赞成使用：
• 在一个DjangoTemplates引擎中的OPTIONS设置’string_if_invalid’ 选项来代替。

Python的Django框架中TEMPLATES项的设置就是这样，欢迎大家参考。。。。

## python删除过期文件的方法详细介绍

python删除过期文件的方法是如何来实现的呢？下面的内容将会通过具体的实例来演示python删除过期文件的方法的实现方法及相关技巧：

```# remove all jpeg image files of an expired modification date = mtime
# you could also use creation date (ctime) or last access date (atime)
# os.stat(filename) returns (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
# tested with Python24  vegaseat 6/7/2005
import os, glob, time
root = 'D:\Vacation\Poland2003\' # one specific folder
#root = 'D:\Vacation\*'     # or all the subfolders too
# expiration date in the format YYYY-MM-DD
xDate = '2003-12-31'
print '-'*50
for folder in glob.glob(root):
print folder
# here .jpg image files, but could be .txt files or whatever
for image in glob.glob(folder + '/*.jpg'):
# retrieves the stats for the current jpeg image file
# the tuple element at index 8 is the last-modified-date
stats = os.stat(image)
# put the two dates into matching format
lastmodDate = time.localtime(stats[8])
expDate = time.strptime(xDate, '%Y-%m-%d')
print image, time.strftime("%m/%d/%y", lastmodDate)
# check if image-last-modified-date is outdated
if expDate > lastmodDate:
try:
print 'Removing', image, time.strftime("(older than %m/%d/%y)", expDate)
#os.remove(image) # commented out for testing
except OSError:
print 'Could not remove', image
```

python删除过期文件的方法就是这样，欢迎大家参考。。。。

## Python实现控制台输入密码的方法详细介绍

Python实现控制台输入密码的方法是如何来实现的呢？下面的内容将会通过具体的实例来演示Python实现控制台输入密码的方法的实现方法及相关技巧：

1. raw_input() :

```pwd = raw_input('password: ')
print pwd
# password: aaa
# aaa
```

Note: 最简单的方法，但是不安全

2. getpass.getpass() :

```import getpass
pwd = getpass.getpass('password: ')
print pwd
# password:
# aaaa
```

Note: 很安全，但是看不到输入的位数，会让人觉得有点不习惯，不知道的还以为没有在输入..

3. msvcrt.getch() :

```import msvcrt, sys
def pwd_input():
chars = []
while True:
newChar = msvcrt.getch()
if newChar in 'rn':
# 如果是换行，则输入结束
print ''
break
elif newChar == 'b':
# 如果是退格，则删除末尾一位
if chars:
del chars[-1]
sys.stdout.write('b')
# 删除一个星号，但是不知道为什么不能执行...
else:
chars.append(newChar)
sys.stdout.write('*')
# 显示为星号
print ''.join(chars)
pwd = pwd_input()
print pwd
# ******
# aaaaaa
```

Note: 解决了第二种方法不能显示输入位数的问题，但是如果按退格键（backspace）的话，虽然实际的是退格了，

Python实现控制台输入密码的方法就是这样，欢迎大家参考。。。。

## python实现旋转图片的方法详细介绍

python实现旋转图片的方法是如何来实现的呢？下面的内容将会通过具体的实例来演示python实现旋转图片的方法的实现方法及相关技巧：

```# rotate an image counter-clockwise using the PIL image library
# free from: http://www.pythonware.com/products/pil/index.htm
# make sure to install PIL after your regular python package is installed
import Image
# open an image file (.bmp,.jpg,.png,.gif)
# change image filename to something you have in the working folder
im1 = Image.open("Donald.gif")
# rotate 60 degrees counter-clockwise
im2 = im1.rotate(60)
# brings up the modified image in a viewer, simply saves the image as
# a bitmap to a temporary file and calls viewer associated with .bmp
# make certain you have an image viewer associated with this file type
im2.show()
# save the rotated image as d.gif to the working folder
# you can save in several different image formats, try d.jpg or d.png
# PIL is pretty powerful stuff and figures it out from the extension
im2.save("d.gif")
```

python实现旋转图片的方法就是这样，欢迎大家参考。。。。

## wxpython实现的windows GUI程序详细介绍

wxpython实现的windows GUI程序是如何来实现的呢？下面的内容将会通过具体的实例来演示wxpython实现的windows GUI程序的实现方法及相关技巧：

```# using a wx.Frame, wx.MenuBar, wx.Menu, wx.Panel, wx.StaticText, wx.Button,
# and a wx.BoxSizer to show a rudimentary wxPython Windows GUI application
# wxPython package from: http://prdownloads.sourceforge.net/wxpython/
# I downloaded: wxPython2.5-win32-ansi-2.5.3.1-py23.exe
# if you have not already done so install the Python compiler first
# I used Python-2.3.4.exe (the Windows installer package for Python23)
# from http://www.python.org/2.3.4/
# tested with Python23   vegaseat   24jan2005
import wx
class Frame1(wx.Frame):
# create a simple windows frame (sometimes called form)
# pos=(ulcX,ulcY) size=(width,height) in pixels
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size=(350, 250))
# create a menubar at the top of the user frame
menuBar = wx.MenuBar()
# create a menu ...
menu = wx.Menu()
# ... add an item to the menu
# tAlt-X creates an accelerator for Exit (Alt + x keys)
# the third parameter is an optional hint that shows up in
# the statusbar when the cursor moves across this menu item
menu.Append(wx.ID_EXIT, "E&xit;tAlt-X", "Exit the program")
# bind the menu event to an event handler, share QuitBtn event
self.Bind(wx.EVT_MENU, self.OnQuitButton, id=wx.ID_EXIT)
# put the menu on the menubar
menuBar.Append(menu, "&File;")
self.SetMenuBar(menuBar)
# create a status bar at the bottom of the frame
self.CreateStatusBar()
# now create a panel (between menubar and statusbar) ...
panel = wx.Panel(self)
# ... put some controls on the panel
text = wx.StaticText(panel, -1, "Hello World!")
text.SetFont(wx.Font(24, wx.SCRIPT, wx.NORMAL, wx.BOLD))
text.SetSize(text.GetBestSize())
quitBtn = wx.Button(panel, -1, "Quit")
messBtn = wx.Button(panel, -1, "Message")
# bind the button events to event handlers
self.Bind(wx.EVT_BUTTON, self.OnQuitButton, quitBtn)
self.Bind(wx.EVT_BUTTON, self.OnMessButton, messBtn)
# use a sizer to layout the controls, stacked vertically
# with a 10 pixel border around each
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.ALL, 10)
sizer.Add(quitBtn, 0, wx.ALL, 10)
sizer.Add(messBtn, 0, wx.ALL, 10)
panel.SetSizer(sizer)
panel.Layout()
def OnQuitButton(self, evt):
# event handler for the Quit button click or Exit menu item
print "See you later alligator! (goes to stdout window)"
wx.Sleep(1)  # 1 second to look at message
self.Close()
def OnMessButton(self, evt):
# event handler for the Message button click
self.SetStatusText('101 Different Ways to Spell "Spam"')
class wxPyApp(wx.App):
def OnInit(self):
# set the title too
frame = Frame1(None, "wxPython GUI 2")
self.SetTopWindow(frame)
frame.Show(True)
return True
# get it going ...
app = wxPyApp(redirect=True)
app.MainLoop()
```

wxpython实现的windows GUI程序就是这样，欢迎大家参考。。。。

## python中集合用法详细介绍

python中集合用法是如何来使用的呢？下面的内容将会通过具体的实例来演示python中集合用法的使用方法及相关技巧：

```# sets are unordered collections of unique hashable elements
# Python23 tested   vegaseat   09mar2005
# Python v2.4 has sets built in
import sets
print "List the functions within module 'sets':"
for funk in dir(sets):
print funk
# create an empty set
set1 = set([])
# now load the set
for k in range(10):
set1.add(k)
print "nLoaded a set with 0 to 9:"
print set1
set1.add(7)
print "Tried to add another 7, but it was already there:"
print set1
# make a list of fruits as you put them into a basket
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
print "nThe original list of fruits:"
print basket
# create a set from the list, removes the duplicates
fruits = sets.Set(basket)
print "nThe set is unique, but the order has changed:"
print fruits
# let's get rid of some duplicate words
str1 = "Senator Strom Thurmond dressed as as Tarzan"
print "nOriginal string:"
print str1
print "A list of the words in the string:"
wrdList1 = str1.split()
print wrdList1
# now create a set of unique words
strSet = sets.Set(wrdList1)
print "The set of the words in the string:"
print strSet
print "Convert set back to string (order has changed!):"
print " ".join(strSet)
print
# comparing two sets, bear with me ...
colorSet1 = sets.Set(['red','green','blue','black','orange','white'])
colorSet2 = sets.Set(['black','maroon','grey','blue'])
print "colorSet1 =", colorSet1
print "colorSet2 =", colorSet2
# same as (colorSet1 - colorSet2)
colorSet3 = colorSet1.difference(colorSet2)
print "nThese are the colors in colorSet1 that are not in colorSet2:"
print colorSet3
# same as (colorSet1 | colorSet2)
colorSet4 = colorSet1.union(colorSet2)
print "nThese are the colors appearing in both sets:"
print colorSet4
# same as (colorSet1 ^ colorSet2)
colorSet5 = colorSet1.symmetric_difference(colorSet2)
print "nThese are the colors in colorSet1 or in colorSet2, but not both:"
print colorSet5
# same as (colorSet1 & colorSet2)
colorSet6 = colorSet1.intersection(colorSet2)
print "nThese are the colors common to colorSet1 and colorSet2:"
print colorSet6
```

python中集合用法就是这样，欢迎大家参考。。。。

## python图像处理之反色实现方法

python图像处理之反色实现方法是如何来实现的呢？下面的内容将会通过具体的实例来演示python图像处理之反色实现方法的实现方法及相关技巧：

Python为：Python2.7.6
OpenCV2.4.10版（可到http://sourceforge.net/projects/opencvlibrary/files/opencv-win/下载）
numpy为：numpy-1.9.1-win32-superpack-python2.7（可到http://sourceforge.net/projects/numpy/files/NumPy/1.9.1/下载）

```import cv2.cv as cv
image = cv.LoadImage('angelababy.jpg',0)
size = (image.width,image.height)
iTmp = cv.CreateImage(size,image.depth,image.nChannels)
for i in range(image.height):
for j in range(image.width):
iTmp[i,j] = 255 - image[i,j]
cv.NamedWindow('image')
cv.NamedWindow('iTmp')
cv.ShowImage('image',image)
cv.ShowImage('iTmp',iTmp)
cv.WaitKey(0)
```

```import cv2.cv as cv
image = cv.LoadImage('angelababy.jpg',1)
size = (image.width,image.height)
iTmp = cv.CreateImage(size,image.depth,image.nChannels)
for i in range(image.height):
for j in range(image.width):
iTmp[i,j] = (255-image[i,j][0],255-image[i,j][1],255-image[i,j][2])
cv.NamedWindow('image')
cv.NamedWindow('iTmp')
cv.ShowImage('image',image)
cv.ShowImage('iTmp',iTmp)
cv.WaitKey(0)
```

python图像处理之反色实现方法就是这样，欢迎大家参考。。。。

## python图像处理之镜像实现方法

python图像处理之镜像实现方法是如何来实现的呢？下面的内容将会通过具体的实例来演示python图像处理之镜像实现方法的实现方法及相关技巧：

I = i

J = N – j + 1

I = M – i + 1

J = j

I = M – i + 1

J = N – j + 1

Python为：Python2.7.6
OpenCV2.4.10版（可到http://sourceforge.net/projects/opencvlibrary/files/opencv-win/下载）
numpy为：numpy-1.9.1-win32-superpack-python2.7（可到http://sourceforge.net/projects/numpy/files/NumPy/1.9.1/下载）

```import cv2.cv as cv
image = cv.LoadImage('angelababy.jpg',1)
size = (image.width,image.height)
iUD = cv.CreateImage(size,image.depth,image.nChannels)
iLR = cv.CreateImage(size,image.depth,image.nChannels)
iAcross = cv.CreateImage(size,image.depth,image.nChannels)
h = image.height
w = image.width
for i in range(h):
for j in range(w):
iUD[h-1-i,j] = image[i,j]
iLR[i,w-1-j] = image[i,j]
iAcross[h-1-i,w-1-j] = image[i,j]
cv.ShowImage('image',image)
cv.ShowImage('iUD',iUD)
cv.ShowImage('iLR',iLR)
cv.ShowImage('iAcross',iAcross)
cv.WaitKey(0)
```

python图像处理之镜像实现方法就是这样，欢迎大家参考。。。。

## wxpython开发的简单GUI计算器实例解析

wxpython开发的简单GUI计算器是如何来实现的呢？下面的内容将会通过具体的实例来演示wxpython开发的简单GUI计算器的实现方法及相关技巧：

```# wxCalc1 a simple GUI calculator using wxPython
# created with the Boa Constructor which generates all the GUI components
# all I had to do is add some code for each button click event
# Boa free from: http://boa-constructor.sourceforge.net/
# note that  boa-constructor-0.3.1.win32.exe
# still uses  wxPythonWIN32-2.4.2.4-Py23.exe
# but is expected to work with wxPython version 2.5 soon
# tested with Python23  vegaseat  26feb2005
from wxPython.wx import *
# some Boa generated global IDs ...
[wxID_WXFRAME1, wxID_WXFRAME1BTN0, wxID_WXFRAME1BTN1, wxID_WXFRAME1BTN2,
wxID_WXFRAME1BTN3, wxID_WXFRAME1BTN4, wxID_WXFRAME1BTN5, wxID_WXFRAME1BTN6,
wxID_WXFRAME1BTN7, wxID_WXFRAME1BTN8, wxID_WXFRAME1BTN9,
wxID_WXFRAME1BTNCLEAR, wxID_WXFRAME1BTNDIV, wxID_WXFRAME1BTNDOT,
wxID_WXFRAME1BTNEQUAL, wxID_WXFRAME1BTNMINUS, wxID_WXFRAME1BTNMULTI,
wxID_WXFRAME1BTNPLUS, wxID_WXFRAME1EDIT,
] = map(lambda _init_ctrls: wxNewId(), range(19))
class wxFrame1(wxFrame):
#startregion, below this marker is Boa generated code do not edit!!!
def _init_ctrls(self, prnt):
# generated method, don't edit
wxFrame.__init__(self, id=wxID_WXFRAME1, name='', parent=prnt,
pos=wxPoint(306, 270), size=wxSize(266, 265),
style=wxDEFAULT_FRAME_STYLE, title='Calculator1')
self.SetClientSize(wxSize(258, 225))
self.SetBackgroundColour(wxColour(0, 128, 0))
self.btn1 = wxButton(id=wxID_WXFRAME1BTN1, label='1', name='btn1',
parent=self, pos=wxPoint(16, 136), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn1, wxID_WXFRAME1BTN1, self.OnBtn1Button)
self.btn2 = wxButton(id=wxID_WXFRAME1BTN2, label='2', name='btn2',
parent=self, pos=wxPoint(64, 136), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn2, wxID_WXFRAME1BTN2, self.OnBtn2Button)
self.btn3 = wxButton(id=wxID_WXFRAME1BTN3, label='3', name='btn3',
parent=self, pos=wxPoint(112, 136), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn3, wxID_WXFRAME1BTN3, self.OnBtn3Button)
self.btn4 = wxButton(id=wxID_WXFRAME1BTN4, label='4', name='btn4',
parent=self, pos=wxPoint(16, 96), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn4, wxID_WXFRAME1BTN4, self.OnBtn4Button)
self.btn5 = wxButton(id=wxID_WXFRAME1BTN5, label='5', name='btn5',
parent=self, pos=wxPoint(64, 96), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn5, wxID_WXFRAME1BTN5, self.OnBtn5Button)
self.btn6 = wxButton(id=wxID_WXFRAME1BTN6, label='6', name='btn6',
parent=self, pos=wxPoint(112, 96), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn6, wxID_WXFRAME1BTN6, self.OnBtn6Button)
self.btn7 = wxButton(id=wxID_WXFRAME1BTN7, label='7', name='btn7',
parent=self, pos=wxPoint(16, 56), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn7, wxID_WXFRAME1BTN7, self.OnBtn7Button)
self.btn8 = wxButton(id=wxID_WXFRAME1BTN8, label='8', name='btn8',
parent=self, pos=wxPoint(64, 56), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn8, wxID_WXFRAME1BTN8, self.OnBtn8Button)
self.btn9 = wxButton(id=wxID_WXFRAME1BTN9, label='9', name='btn9',
parent=self, pos=wxPoint(112, 56), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn9, wxID_WXFRAME1BTN9, self.OnBtn9Button)
self.btn0 = wxButton(id=wxID_WXFRAME1BTN0, label='0', name='btn0',
parent=self, pos=wxPoint(16, 176), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btn0, wxID_WXFRAME1BTN0, self.OnBtn0Button)
self.btnDot = wxButton(id=wxID_WXFRAME1BTNDOT, label='.', name='btnDot',
parent=self, pos=wxPoint(64, 176), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btnDot, wxID_WXFRAME1BTNDOT, self.OnBtnDotButton)
self.btnEqual = wxButton(id=wxID_WXFRAME1BTNEQUAL, label='=',
name='btnEqual', parent=self, pos=wxPoint(112, 176),
size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btnEqual, wxID_WXFRAME1BTNEQUAL, self.OnBtnEqualButton)
self.edit = wxTextCtrl(id=wxID_WXFRAME1EDIT, name='edit', parent=self,
pos=wxPoint(16, 16), size=wxSize(224, 24), style=0, value='')
self.btnPlus = wxButton(id=wxID_WXFRAME1BTNPLUS, label='+',
name='btnPlus', parent=self, pos=wxPoint(160, 56), size=wxSize(32,
32), style=0)
EVT_BUTTON(self.btnPlus, wxID_WXFRAME1BTNPLUS, self.OnBtnPlusButton)
self.btnMinus = wxButton(id=wxID_WXFRAME1BTNMINUS, label='-',
name='btnMinus', parent=self, pos=wxPoint(160, 96),
size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btnMinus, wxID_WXFRAME1BTNMINUS, self.OnBtnMinusButton)
self.btnMulti = wxButton(id=wxID_WXFRAME1BTNMULTI, label='*',
name='btnMulti', parent=self, pos=wxPoint(160, 136),
size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btnMulti, wxID_WXFRAME1BTNMULTI, self.OnBtnMultiButton)
self.btnDiv = wxButton(id=wxID_WXFRAME1BTNDIV, label='/', name='btnDiv',
parent=self, pos=wxPoint(160, 176), size=wxSize(32, 32), style=0)
EVT_BUTTON(self.btnDiv, wxID_WXFRAME1BTNDIV, self.OnBtnDivButton)
self.btnClear = wxButton(id=wxID_WXFRAME1BTNCLEAR, label='C',
name='btnClear', parent=self, pos=wxPoint(208, 56),
size=wxSize(32, 32), style=0)
self.btnClear.SetToolTipString('btnClear')
EVT_BUTTON(self.btnClear, wxID_WXFRAME1BTNCLEAR, self.OnBtnClearButton)
def __init__(self, parent):
self._init_ctrls(parent)
#endregion, above this marker is Boa generated code, do not edit!!!
# now respond to all the button click events ...
def OnBtn0Button(self, event):
val = '0'
# get existing edit box text
txt = self.edit.GetValue()
# append text
txt = txt + val
# update edit box text
self.edit.SetValue(txt)
def OnBtn1Button(self, event):
val = '1'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn2Button(self, event):
val = '2'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn3Button(self, event):
val = '3'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn4Button(self, event):
val = '4'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn5Button(self, event):
val = '5'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn6Button(self, event):
val = '6'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn7Button(self, event):
val = '7'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn8Button(self, event):
val = '8'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtn9Button(self, event):
val = '9'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtnDotButton(self, event):
val = '.'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtnEqualButton(self, event):
txt = self.edit.GetValue()
# needs to contain a float so eg. 3/5 is 3/5.0
# otherwise division 3/5 would result in zero
if '/' in txt:
if '.' not in txt:
txt = txt + '.0'
# now evaluate the math string
txt = repr(eval(txt))
# and show result in edit box
self.edit.SetValue(txt)
def OnBtnPlusButton(self, event):
val = '+'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtnMinusButton(self, event):
val = '-'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtnMultiButton(self, event):
val = '*'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtnDivButton(self, event):
val = '/'
txt = self.edit.GetValue()
txt = txt + val
self.edit.SetValue(txt)
def OnBtnClearButton(self, event):
self.edit.SetValue('')
# -------------------- end of class wxFrame1 ----------------------
def create(parent):
return wxFrame1(parent)
class BoaApp(wxApp):
def OnInit(self):
wxInitAllImageHandlers()
self.main = create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
```

wxpython开发的简单GUI计算器就是这样，欢迎大家参考。。。。

## Python如何使用win32com库播放mp3文件

Python使用win32com库播放mp3文件是如何来实现的呢？下面的内容将会通过具体的实例来演示Python使用win32com库播放mp3文件的实现方法及相关技巧：

```# count lines, sentences, and words of a text file
# set all the counters to zero
lines, blanklines, sentences, words = 0, 0, 0, 0
print '-' * 50
try:
# use a text file you have, or google for this one ...
filename = 'GettysburgAddress.txt'
textf = open(filename, 'r')
except IOError:
print 'Cannot open file %s for reading' % filename
import sys
sys.exit(0)
# reads one line at a time
for line in textf:
print line,  # test
lines += 1
if line.startswith('n'):
blanklines += 1
else:
# assume that each sentence ends with . or ! or &#63;
# so simply count these characters
sentences += line.count('.') + line.count('!') + line.count('&#63;')
# create a list of words
# use None to split at any whitespace regardless of length
# so for instance double space counts as one space
tempwords = line.split(None)
print tempwords # test
# word total count
words += len(tempwords)
textf.close()
print '-' * 50
print "Lines   : ", lines
print "Blank lines: ", blanklines
print "Sentences : ", sentences
print "Words   : ", words
# optional console wait for keypress
from msvcrt import getch
getch()
```

Python使用win32com库播放mp3文件就是这样，欢迎大家参考。。。。

## Python统计文本文件内单词数量的方法介绍

Python统计文本文件内单词数量是如何来实现的呢？下面的内容将会通过具体的实例来演示Python统计文本文件内单词数量的实现方法及相关技巧：

```# count lines, sentences, and words of a text file
# set all the counters to zero
lines, blanklines, sentences, words = 0, 0, 0, 0
print '-' * 50
try:
# use a text file you have, or google for this one ...
filename = 'GettysburgAddress.txt'
textf = open(filename, 'r')
except IOError:
print 'Cannot open file %s for reading' % filename
import sys
sys.exit(0)
# reads one line at a time
for line in textf:
print line,  # test
lines += 1
if line.startswith('n'):
blanklines += 1
else:
# assume that each sentence ends with . or ! or &#63;
# so simply count these characters
sentences += line.count('.') + line.count('!') + line.count('&#63;')
# create a list of words
# use None to split at any whitespace regardless of length
# so for instance double space counts as one space
tempwords = line.split(None)
print tempwords # test
# word total count
words += len(tempwords)
textf.close()
print '-' * 50
print "Lines   : ", lines
print "Blank lines: ", blanklines
print "Sentences : ", sentences
print "Words   : ", words
# optional console wait for keypress
from msvcrt import getch
getch()
```

Python统计文本文件内单词数量就是这样，欢迎大家参考。。。。

## Python比较两段文本不同之处的方法介绍

Python比较两段文本不同之处是如何来实现的呢？下面的内容将会通过具体的实例来演示Python比较两段文本不同之处的实现方法及相关技巧：

```# find the difference between two texts
# tested with Python24  vegaseat 6/2/2005
import difflib
text1 = """The World's Shortest Books:
Human Rights Advances in China
"My Plan to Find the Real Killers" by OJ Simpson
"Strom Thurmond: Intelligent Quotes"
America's Most Popular Lawyers
Career Opportunities for History Majors
Different Ways to Spell "Bob"
Dr. Kevorkian's Collection of Motivational Speeches
Spotted Owl Recipes by the EPA
The Engineer's Guide to Fashion
Ralph Nader's List of Pleasures
"""
text2 = """The World's Shortest Books:
Human Rights Advances in China
"My Plan to Find the Real Killers" by OJ Simpson
"Strom Thurmond: Intelligent Quotes"
America's Most Popular Lawyers
Career Opportunities for History Majors
Different Ways to Sell "Bob"
Dr. Kevorkian's Collection of Motivational Speeches
Spotted Owl Recipes by the EPA
The Engineer's Guide to Passion
Ralph Nader's List of Pleasures
"""
# create a list of lines in text1
text1Lines = text1.splitlines(1)
print "Lines of text1:"
for line in text1Lines:
print line,
print
# dito for text2
text2Lines = text2.splitlines(1)
print "Lines of text2:"
for line in text2Lines:
print line,
print
diffInstance = difflib.Differ()
diffList = list(diffInstance.compare(text1Lines, text2Lines))
print '-'*50
print "Lines different in text1 from text2:"
for line in diffList:
if line[0] == '-':
print line,
```

Python比较两段文本不同之处就是这样，欢迎大家参考。。。。

## Python Django框架中的settings文件的部署介绍

django在一个项目的目录结构划分方面缺乏必要的规范，因此不同人的项目组织形式也千奇百怪，而且也很难说谁的做法就比较好。我根据自己的项目组织习惯，发布了一个项目dj-scaffold。

local_settings的弊病

```try:
from local_settings import *
except:
pass
```

```|~settings/
| |-__init__.py
| |-base.py   #默认配置信息
| |-dev.py    #开发环境的配置
| |-local.sample    #本地的扩展配置在dev和production的最后进行import
| |-pre.sample    #设置当前使用的配置为生产环境还是开发环境
| `-production.py    #生产环境的配置
```

```DJANGO_SETTINGS_MODULE
```

django的admin脚本提供了settings参数用于指定当前使用的配置文件

```django-admin.py shell --settings=settings.dev
```

```deploy.wsgi
os.environ['DJANGO_SETTINGS_MODULE'] = settings.production
```

```SETTINGS = 'production' #dev
```

Python Django框架中的settings文件的部署就是这样，欢迎大家参考。。。。

## Python Django框架中的dj-scaffold项目介绍

django1.3新加入了一个静态资源管理的app，django.contrib.staticfiles。在以往的django版本中，静态资源的管理一向都是个问题。部分app发布的时候会带上静态资源文件，在部署的时候你必须手动从各个app中将这些静态资源文件复制到同一个static目录。在引入staticfiles后，你只需要执行./manage.py collectstatic就可以很方便的将所用到app中的静态资源复制到同一目录。

staticfiles的引入，方便了django静态文件的管理，不过感觉staticfiles的文档写的并不是太清楚，初次使用的时候还是让我有些困惑。

• STATIC_ROOT：运行manage.py collectstatic后静态文件将复制到的目录。注意：不要把你项目的静态文件放到这个目录。这个目录只有在运行collectstatic时才会用到。我最开始想当然的以为这个目录和MEDIA_ROOT的作用是相同的，致使在开发环境下一直无法找到静态文件。
• STATIC_URL：设置的static file的起始url，这个只可以在template里面引用到。这个参数和MEDIA_URL的含义差不多。
• STATICFILES_DIRS：除了各个app的static目录以外还需要管理的静态文件位置，比如项目公共的静态文件差不多。和TEMPLATE_DIRS的含义差不多。
• 各个APP下static/目录下的静态文件django的开发服务器会自动找到，这点和以前APP下的templates目录差不多。
• 在urls.py中加入静态文件处理的代码
```  from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
```

Python Django框架中的dj-scaffold项目就是这样，欢迎大家参考。。。。

## Python Django框架中的staticfiles使用方法介绍

Python Django框架中的staticfiles是如何来使用的呢？下面的内容将会通过具体的实例来演示Python Django框架中的staticfiles的使用方法及相关技巧：

django1.3新加入了一个静态资源管理的app，django.contrib.staticfiles。在以往的django版本中，静态资源的管理一向都是个问题。部分app发布的时候会带上静态资源文件，在部署的时候你必须手动从各个app中将这些静态资源文件复制到同一个static目录。在引入staticfiles后，你只需要执行./manage.py collectstatic就可以很方便的将所用到app中的静态资源复制到同一目录。

staticfiles的引入，方便了django静态文件的管理，不过感觉staticfiles的文档写的并不是太清楚，初次使用的时候还是让我有些困惑。

• STATIC_ROOT：运行manage.py collectstatic后静态文件将复制到的目录。注意：不要把你项目的静态文件放到这个目录。这个目录只有在运行collectstatic时才会用到。我最开始想当然的以为这个目录和MEDIA_ROOT的作用是相同的，致使在开发环境下一直无法找到静态文件。
• STATIC_URL：设置的static file的起始url，这个只可以在template里面引用到。这个参数和MEDIA_URL的含义差不多。
• STATICFILES_DIRS：除了各个app的static目录以外还需要管理的静态文件位置，比如项目公共的静态文件差不多。和TEMPLATE_DIRS的含义差不多。
• 各个APP下static/目录下的静态文件django的开发服务器会自动找到，这点和以前APP下的templates目录差不多。
• 在urls.py中加入静态文件处理的代码
```  from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
```

Python Django框架中的staticfiles就是这样，欢迎大家参考。。。。

## Python如何使用url_helper来简化Django框架里url配置

Python使用url_helper来简化Django框架里url配置是如何来实现的呢？下面的内容将会通过具体的实例来演示Python使用url_helper来简化Django框架里url配置的实现方法及相关技巧：

django的url采用正则表达式进行配置，虽然强大却也广为诟病。反对者们认为django的url配置过于繁琐，且不支持默认的路由功能。

url_helper的具体用法请参考具体的例子：

url_helper下载/范例

url的默认路由

```from url_helper import execute, url_
import views
urlpatterns += patterns('',
url(r'^(&#63;P<urls>.*)', execute, {'views': views}),
)
```

```#/edit/4/
def edit(request, n="id"):
html = """ edit object: %s""" % n
return HttpResponse(html)
```

```#url_(r'/space/:username/:tag/', views.url_),
#/space/vicalloy/just/
def url_(request, username, tag):
html = """ username: %s <br/> tag: %s""" % (username, tag)
return HttpResponse(html)
```

url_helper的完整代码

```#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django import http
from django.conf.urls.defaults import url
import re
def execute(request, urls, views):
"""
urls [methodName/]param1/param2/.../
methodName default index
"""
def get_method(views, methodName):
try:
return getattr(views, methodName)
except Exception, e:
return None
method = None
params = [e for e in urls.split("/") if e]
params.reverse()
if params:
method = get_method(views, params.pop())
if not method:
method = get_method(views, 'index')
if not method:
raise http.Http404('The requested admin page does not exist.')
return method(request, *params)
def url_(*args,**dic):
regex = args[0]
if regex[0] == "/":
regex = regex[1:]
regex = '^' + regex
regex = regex + '\$'
regex = re.sub(":[^/]+",
lambda matchobj: "(&#63;P<%s>[^/]+)" % matchobj.group(0)[1:],
regex)
return url(regex, *args[1:], **dic)
```

Python使用url_helper来简化Django框架里url配置就是这样，欢迎大家参考。。。。