Python:列出子进程调用pcregepmultilin的匹配模式列表

2024-06-12 05:58:10 发布

您现在位置:Python中文网/ 问答频道 /正文

TLDR:有没有一种干净的方法来列出subprocess.check_输出('pcregep'、'-M'、'-e'、图案、文件)?

我使用python的subprocess.check_output()调用pcregrep -M。通常,我会通过调用splitlines()来分离结果,但由于我要寻找多行模式,这行不通。我很难找到一个干净的方法来创建匹配模式的列表,其中列表的每个条目都是一个单独的匹配模式。在

下面是一个简单的示例文件

module test_module(
    input wire in0,
    input wire in1,
    input wire in2,
    input wire cond,
    input wire cond2,
    output wire out0,
    output wire out1
);

assign out0 = (in0 & in1 & in2);
assign out1 = cond1 ? in1 & in2 :
              cond2 ? in1 || in2 :
              in0;

以下是我的python代码

^{pr2}$

这是输出

output_str[0] = 
assign out0 = in0 & in1 & in2
output_str[1] = 
assign out1 = cond1 ? in1 & in2 :
              cond2 ? in1 || in2 :
              in0
output_str[2] = 

如果我能做点像

output_list = subprocess.check_output('pcregrep', -M, -e, <pattern>, <file>).split(<multiline_delimiter>)

不需要创建垃圾来清理(空白列表项),甚至不需要为split()设置一个独立于模式的分隔符。在

有没有一种干净的方法来创建匹配的多行模式列表?


Tags: 方法列表inputoutputcheck模式subprocessassign
2条回答

根据Casimir et Hippolyte的评论,以及非常有用的帖子How do I re.search or re.match on a whole file without reading it all into memory?,我在文件中使用re而不是对pcregep的外部调用,并使用re.findall(pattern, file, re.MULTILINE)

完整的解决方案(只对引用的帖子稍作修改)

#!/usr/bin/env python
import re, mmap

filename = "/home/<username>/pcregrep_file.sv"
with open(filename, 'r+') as f:
    data = mmap.mmap(f.fileno(), 0)
    output_str = re.findall(r'^\s*assign\s+\bct_ela\b[^;]+;', data, re.MULTILINE)
    for i, l in enumerate(output_str):
    print "output_str[%d] = '%s'" % (i,l)

创建所需列表。在

别那样做。如果出于某种原因不能使用Python正则表达式模块,只需使用Python bindings for pcre。在

相关问题 更多 >