7月 03

在linux下用python读取其他操作系统编写的配置文件

  在windows、mac、linux下编写的配置文件会有头部或者换行有区别。为了分析方便简单做个记录,只为演示,代码并不完整,需要自己修改

def conf(conf_context):
    # 替换window或mac操作系统下的换行符
    import re
    _get_file = re.sub(r'(\r\n|\r|\n)', '\n', conf_context)
    # 将配置放在内存中
    import StringIO
    _tmp_file = StringIO.StringIO()
    # 将文件写入内存
    _tmp_file.write(_get_file)
    _tmp_file.seek(0)
    # 如果是在window下编辑的文件将,utf-8 BOM开始的头替换掉
    if _tmp_file.read(3).startswith('\xef\xbb\xbf'):
        _tmp_file.seek(3)
    else:
        _tmp_file.seek(0)
    # 导入配置
    import ConfigParser
    try:
        cf = ConfigParser.SafeConfigParser()
        cf.readfp(_tmp_file)
        config_list = cf.sections()
    except:
        _tmp_file.close()
        return "error"
    _tmp_file.close()
    return "ok"
6月 07

python 对字符串的加密解密

  需求是是要将密码存在数据库里,所以要加密解密是可逆的,在数据库里不要有特殊字符,防止数据库备份和恢复中出错。
  安装PyCrypto,可以用AES和DES。我使用DES加解密。加密后将密文转为16进制,在入库。测试代码如下。

#!/bin/python
#-*- coding:utf-8 -*-
# Filename:
# Revision:    
# Date:        2013-06-07
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
# easy_install PyCrypto
from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import DES
key = '12345678' #长度必须是8位的
text = 'simonzhang.net  '  #长度必须是8的倍数,我用空格补的
# 实例化
obj = DES.new(key)
# 加密
cryp = obj.encrypt(text)
pass_hex = b2a_hex(cryp)
print pass_hex
print '=' * 20
# 解密
get_cryp = a2b_hex(pass_hex)
after_text = obj.decrypt(get_cryp)
print after_text

测试代码

6月 05

python 抓取页面

  最初只是简单抓取没有问题,现在要在线上做抓取时发现很多问题。比如:长时间使用报500错误,需要cookie,有的网站有gzip压缩。本段代码已经解决以上问题,但是字符集问题没有处理,因为我要抓的页面没字符问题。我将代码放在tornado上跑,分析的服务器请求后直接抓取返回信息给分析的服务器。

import urllib2
import cookielib

def get_url_context(_url):
    # cookie
    cj = cookielib.CookieJar()
    _myopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    _req = urllib2.Request("http://%s" % _url)
    # add head
    _req.add_header("Accept-Language", "zh-cn")
    _req.add_header("Content-Type", "text/html; charset=utf-8")
    _req.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)")
    # open
    _get_page_data = _myopener.open(_req)
    _get_headers = _get_page_data.info()
    _get_rawdata = _get_page_data.read()
    _get_page_data.close()
    # check gzip
    if ('Content-Encoding' in _get_headers and _get_headers['Content-Encoding']) or \
        ('content-encoding' in _get_headers and _get_headers['content-encoding']):
        import gzip
        import StringIO
        data = StringIO.StringIO(_get_rawdata)
        gz = gzip.GzipFile(fileobj=data)
        _get_rawdata = gz.read()
        gz.close()
    return _get_rawdata

get_page测试代码

12月 04

python 源码删除注释并编译成字节码

  上线需要,将py的源码中注释删掉,然后编译成字节码,这样加载速度会比较快。写此脚本主要是为了删除注释。当然如果上线不想放py源码,则在最后增加删除源码即可。我把这个代码起名为咕噜咕噜。python 源码删除注释并编译。

#!/bin/env python
# -*- coding:utf-8 -*-
# -------------------------------
# Filename:    
# Revision:
# Date:        2012-12-3
# Author:      simonzhang
# Email:       simon-zzm@163.com
# Web:         www.simonzhang.net 
# -------------------------------
import os
import re
import sys
import shutil
import compileall


def delete_Notes(py_file):
    # 原始文件只读打开,处理文件追加打开
    _tmp_sr_file = open(py_file, "rb").readlines()
    _tmp_de_file = open("%s.swp" % py_file, "ab")
    _skip_status = 0
    _now_line = 0
    _multi_count = 0 
    # 循环处理
    for line in _tmp_sr_file:
        # 跳过前10行,因为我的开头注释有10行
        if _now_line > 10:
            # 获取开头一位和三位
            try:
                _single_row_notes = line.strip()[0]
            except:
                _single_row_notes = ""
            try: 
                _multi_row_notes = line.strip()[0:3]
            except:
                _multi_row_notes = ""
            # 获取行是否为注释
            if _single_row_notes == "#":
                _skip_status = 1
            elif _multi_row_notes == "'''":
                if _multi_count == 0:
                    _skip_status = 1
                    _multi_count = 1
                else:
                    _skip_status = 1
                    _multi_count = 0
            elif _multi_count == 1:
                _skip_status = 1
            else:
                _skip_status = 0
        else:
            _skip_status = 0
        # 判断是否跳过写入
        if _skip_status == 0:
            _tmp_de_file.write(line)
        _now_line += 1
    _tmp_de_file.close()
    # 处理完毕将临时文件处理为原始文件
    shutil.move("%s.swp" % py_file, py_file)
        

def main():
    _get_src_path = sys.argv[1]
    _get_dec_path = sys.argv[2]
    if os.path.exists(_get_src_path):
        # 拷贝原始文件夹
        shutil.copytree(_get_src_path, _get_dec_path)
        # 删除原始文件中的注释
        find_py_file = re.compile(r"^.*\.py$")
        find_walk = os.walk(_get_dec_path)
        for path,dirs,files in find_walk:
            for f in files:
                if find_py_file.search(f):
                    delete_Notes("%s/%s" % (path, f))
        # 编译成字节码
        compileall.compile_dir(_get_dec_path)
    else:
        print "Path Error!"

if __name__ == "__main__":
    main()

使用方法,
gulugulu.py 源码路径 目标路径

python 源码删除注释并编译

7月 19

python邮件内容格式问题

发送邮件,内容需要是html格式,content为邮件内容,我使用的都是utf-8编码。实现如下:

引用
from email.mime.text import MIMEText

以网页方式发送
msg = MIMEText(content.encode(‘utf8′), _subtype=’html’, _charset=’utf8′)

以纯文本方式发送
msg = MIMEText(content.encode(‘utf8′), _subtype=’plain’, _charset=’utf8′)

默认以纯文本方式发送