2月 13

python 字典的保存于读取

用字典做了文本数据的统计,但是还没有统计完,需要第二天继续,所以
用到了数据持久化部分。简单记录字典的保存和导出。

import pickle
# create dict
list = {“01″:02,”02″:03,”03”:04}
# save dict
f1 = open(“E:\\test.txt”,”wb”)
pickle.dump(list, f1)
f1.close()
# load dict
f2 = open(“E:\\test.txt”,”rb”)
load_list = pickle.load(f2)
f2.close()
# print
print load_list

理论上也可以放入数据库中,但是我没有测试。

12月 16

python 在linux上处理图片的错误处理

在CentOS 5.4 64位上安装了python2.6和PIL模块处理图片。
遇到问题1:
Traceback (most recent call last):
 File “aimg.py”, line 3, in
  img.save(‘/program/upload/b.jpg’,’JPEG’)
 File “/usr/local/lib/python2.6/site-packages/PIL-1.1.7-py2.6-linux-

x86_64.egg/Image.py”, line 1406, in save
 self.load()
 File “/usr/local/lib/python2.6/site-packages/PIL-1.1.7-py2.6-linux-

x86_64.egg/ImageFile.py”, line 189, in load
  d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
 File “/usr/local/lib/python2.6/site-packages/PIL-1.1.7-py2.6-linux-

x86_64.egg/Image.py”, line 385, in _getdecoder
  raise IOError(“decoder %s not available” % decoder_name)
IOError: decoder jpeg not available

处理方法:
# rm -rf /usr/local/lib/python2.6/site-packages/PIL-1.1.7-py2.6-linux-x86_64.egg
# rm -rf /usr/local/lib/python2.6/site-packages/PIL.pth
# yum install -y libjpeg* freetype* zlib*
# easy_install PIL

遇到问题2:
WARNING: ” not a valid package name; please use only.-separated package names in setup.py
_imaging.c:75:20: error: Python.h: No such file or directory
In file included from libImaging/Imaging.h:14,
from _imaging.c:77:
libImaging/ImPlatform.h:14:2: error: #error Sorry, this library requires support for ANSI prototypes.
libImaging/ImPlatform.h:17:2: error: #error Sorry, this library requires ANSI header files.
libImaging/ImPlatform.h:55:2: error: #error Cannot find required 32-bit integer type
In file included from _imaging.c:77

处理方法:
yum install python-imaging
yum install python-dev
python PIL

再次测试问题解决。

10月 11

突发想法:python 随机产生双色球投注

【2011-10-11 张子萌】
今天用python做redis的测试,主要测试随机读redis的效率。突发想法这个产生双色球的结果挺方便的。33选6 ,呵呵呵呵呵。

#!/bin/env python
# -*- coding:utf-8 -*-
import random
list = [“01″,”02″,”03″,”04″,”05″,”06″,”07″,”08″,”09″,”10″,”11”,
“11”,”12″,”13″,”14″,”15″,”16″,”17″,”18″,”19″,”20″,”21″,
“21”,”22″,”23″,”24″,”25″,”26″,”27″,”28″,”29″,”30″,”31″,
“32”,”33″]
get_array = random.sample(list,6)
print “%s”%get_array

10月 04

python 链接 redis 测试

[2011-9-11 张子萌]
[2012-5-27 张子萌 修改]
  安装支持的模块,简单的方法是使用easy_install
# easy_install redis

  也可以下载安装包手动安装。做个简单的写入测试,使用有664039行的密码表,将密码放到redis中。代码如下:

#!/usr/bin/env python
import redis
def main():
    r = redis.Redis(host='192.168.1.200', port=6379, db=0)
    w_pass=open('big_pass.txt','r').readlines()
    next_line=0
    count_lines=len(w_pass)
    while next_line+1 < count_lines:
        r.set(str(next_line),w_pass[next_line])
        next_line=next_line+1
    print 'Game over!'
if __name__=='__main__':
    main()

测试服务器为一个Xeon(TM)双核 3.20GHz 的 cpu,内存4G。
a)写入
用两台机器做测试。两台机器均在一个千兆局域网内。实验很简单所以只记录了cpu的负载和脚本运行时间。
# time python test_redis1.py
Game over!
real 4m16.878s
user 0m55.910s
sys 0m16.879s

cpu部分
远端机缓存 load average: 1.46, 1.26, 1.34

Redis服务器 load average: 0.52, 0.30, 0.22

单台服务器本地测试:
# time python python_redis.py
Game over!
real 1m32.065s
user 1m2.643s
sys 0m17.890s

cpu部分
load average: 1.32, 0.57, 0.32

b)存环从reids中读取所有数据,测试结果如下:
两台服务器:
# time python test_redis1.py
Game over!

real 4m32.776s
user 1m3.687s
sys 0m17.675s

Redis服务器Cpu部分
load average: 0.90, 0.96, 0.69
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
27525 root 15 0 117m 110m 712 S 7.3 2.8 2:55.36 redis-server

单台服务器本地测试:
# time python python_redis.py
Game over!

real 1m44.790s
user 1m9.294s
sys 0m19.031s

Cpu部分
load average: 1.36, 0.92, 0.63

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
3255 root 18 0 153m 47m 2640 R 87.1 1.2 0:29.43 python
27525 root 15 0 117m 110m 712 S 33.1 2.8 2:29.26 redis-server

Redis的其它操作并未测试,但是从当前测试看,单进程每秒读写差不多再7000-8000,cpu使用维持在百分之三十多,确实效率不错。
注为了测试方便,我的redis服务没有加密码。如需加访问密码或有其它需参数,参考如下:
host='localhost'
port=6379
db=0
password=None
socket_timeout=None
connection_pool=None
charset='utf-8'
errors='strict'
unix_socket_path=None

9月 28

pyinotify监控文件和文件夹变化

【2011-9-28 张子萌】

之前写了脚本,死循环调用inotifywait监控文件夹,如果文件有变动,则启动

rsync进行同步。但是当前需求有点变化,文件要按照日期建文件夹进行存储,

且文件变化很快,如果直接监控最顶级目录系统资源将消耗很大,所以考虑还是自

写一下好,如果系统资源量变化大,且不用时时同步时可以根据文件变动对变动

对文件进行记录,可以按照优先规则进行同步。

官方网站 : http://trac.dbzteam.org/pyinotify

系统要求:Linux kernel with inotify 2.6.13

Python 2.4

直接使用easy_install安装非常简单

# sudo easy_install pyinotify

如果不能联网,则需要直接下载压缩包,进行编译安装。

首先测试下是否可用:

使用以下命令监控/tmp文件夹,

# python -m pyinotify /tmp

/tmp文件夹下新建1.txt,并随后进行删除。看到显示的记录如下:

效果不错,继续向下进行。只要有创建、删除和关闭写就打印出变化的文件或目录,代码如下:

import re

import pyinotify

wm = pyinotify.WatchManager()

mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE

class EventHandler(pyinotify.ProcessEvent):

def process_IN_CREATE(self, event):

self.rebuild(event)

def process_IN_DELETE(self, event):

self.rebuild(event)

def process_IN_CLOSE_WRITE(self, event):

self.rebuild(event)

def rebuild(self, event):

chang_name=re.compile(“.+.swp$|.+.swx$|.+.swpx$”)

if not chang_name.match(event.pathname):

print event.pathname

handler = EventHandler()

notifier = pyinotify.Notifier(wm, handler)

wdd = wm.add_watch(‘/tmp’, mask, rec=True,auto_add=True )

notifier.loop()

代码里使用正则表达式过滤因为使用vim打开文件产生的缓存文件。也可以用exclude_filter方法

在官方文档中例子如下,但是我测试多次没有成功,所以直接用正则过滤。

# Exclude patterns from list

excl_lst = [‘^/etc/apache[2]?/’,

‘^/etc/rc.*’,

‘^/etc/hostname’,

&nb
sp;
‘^/etc/hosts’,

‘^/etc/(fs|m)tab’,

‘^/etc/cron..*’]

excl = pyinotify.ExcludeFilter(excl_lst)

# Add watches

res = wm.add_watch([‘/etc/hostname’, ‘/etc/cups’, ‘/etc/rc0.d’],

pyinotify.ALL_EVENTS, rec=True, exclude_filter=excl)

如果监控文件太多,需要对系统做一下修改sysctl -n -w fs.inotify.max_user_watches=16384