代码之家  ›  专栏  ›  技术社区  ›  Makis

将popen.communication()输出与正则表达式匹配不起作用

  •  1
  • Makis  · 技术社区  · 14 年前

    我的代码大致如下(整个代码太长,无法复制到这里):

    import re
    from subprocess import Popen, PIPE
    
    goodOutput = re.compile(r'\S+: 0x[0-9a-fA-F]{8} \d \d\s+->\s+0x[0-9a-fA-F]{8}')
    
    p = Popen(['/tmp/myexe', param], stdout=PIPE, stderr=PIPE, cwd='/tmp')
    
    stdout, stderr = p.communicate()
    
    ret = goodOutput.match(stdout)
    if ret == None:
       print "No match in: " + stdout
    

    match()与此不匹配,但如果我从print语句复制stdout,并使用上面脚本中的字符串作为stdout的值,它将匹配。所以regexp模式应该没问题。另外,如果我从stdin(stdout=sys.input.read())读取字符串,它会再次工作。

    我也尝试过rstrip()stdout,但这也没有帮助(另外,Match()不应该使这变得不必要吗?).

    当我用repr()打印stdout时,字符串看起来像

    'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00\n'
    

    如果我尝试将()与此匹配,它将不匹配。这是制表符和换行符的问题吗?如果是,我应该怎么做?

    3 回复  |  直到 14 年前
        1
  •  1
  •   Tim Pietzcker    14 年前

    似乎仍然有在你的regex或错误导致它不匹配(无关 } ,空白太多)。

    尝试

    goodOutput = re.compile(r"\s*[^:]:s*0x[0-9a-fA-F]{8}\s+\d\s+\d\s+->\s+0x[0-9a-fA-F]{8}"`
    

    看看有没有帮助。

    另外,试试看 re.search() VS re.match() 看看这有什么不同。

        2
  •  0
  •   kriss    14 年前

    您确定stdout中没有前导空格或不可见字符吗?如果你复制粘贴它们后面的内容,而不是这些字符,它将解释为什么你的测试“手工”有效。

    如果是这样,也许你想做一个 re.search (在任何地方匹配)而不是 re.match (在开头匹配)或删除这些前导字符。

        3
  •  0
  •   SilentGhost    14 年前

    您的regex有一些随机字符,其版本正确,所有内容都匹配:

    >>> s = 'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00\n'
    >>> re.match(r'\S+: 0x[0-9a-f]{8} \d \d\s+->\s+0x[0-9a-f]{8}', s, re.I).group()
    'xxx[a]: 0xff2eff00 4 7\t->\t0xff2eff00'