星期一, 四月 14, 2008

Python open() 的 'U' 参数

看下面的一个 Python 脚本:
#!/usr/bin/python
# -*- encoding: utf-8 -*-

__author__ = "周鹏 "
__date__ = "14 April 2008"
__version__ = "0.1"

import re
import os,sys
import subprocess
from subprocess import PIPE

class CheckFail:
def __init__(self, message):
self.message = message

class CheckPoint:
"""
过滤 dmesg 输出以检查是否有硬件故障
"""
def __init__(self, args, info, config):
self.args = args
self.info = info
self.config = config
self.status = "OK"
self.strerr = ""
self.L_regexp = []
re_empty_line = re.compile("^\s*$")
for line in open(config, 'rU'):
if line.startswith("#"): continue
elif re_empty_line.match(line): continue
line = r"%s" % line.strip("\n")
self.L_regexp.append(re.compile(line))

def run(self):
pipe = subprocess.Popen(["dmesg"], stdout=PIPE, stderr=PIPE)
for line in pipe.stdout.readlines():
line = line.strip("\n")
for ro in self.L_regexp:
mo = ro.search(line)
if mo:
return "FAIL", "dmesg 硬件或核心故障: %s" % line
return self.status, self.strerr
这里使用 open(fname, 'rU') 从一个配置文件 config 中读取需要的过滤模式,然后对 dmesg 的输出进行匹配,因为开始编辑这个 config 文件的时候时在 Windows 下面,所以如果仅仅使用 'r',则读到的将是带 \r 作为换行符的串,那么当与在 Linux 下的文本进行过滤时,则完全不可能真正进行匹配!

所以这里使用了一个 'U' 参数。

1 条评论:

wayne 说...

U这个参数比较生僻,从来没有用过......
直接line.strip(),把后面的所有空白符去掉不是更直接?