【发布时间】:2017-03-21 22:00:25
【问题描述】:
TLDR:有没有一种简洁的方法来为 subprocess.check_output('pcregrep', '-M', '-e', pattern, file) 制作条目列表?
我正在使用 python 的subprocess.check_output() 调用pcregrep -M。通常我会通过调用splitlines() 来分隔结果,但由于我正在寻找多行模式,所以这是行不通的。我很难找到一种干净的方法来创建匹配模式列表,其中列表的每个条目都是一个单独的匹配模式。
这是一个我正在 pcgrep'ing 的简单示例文件
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 代码
#!/usr/bin/env python
import subprocess, re
output_str = subprocess.check_output(['pcregrep', '-M', '-e',"^\s*assign\\s+\\bout0\\b[^;]+;",
"/home/<username>/pcregrep_file.sv"]).split(';')
# Print out the matches
for idx, line in enumerate(output_str):
print "output_str[%d] = %s" % (idx, line)
# Clear out the whitespace list entries
output_str = [line for line in output_str if re.match(\S+, line)]
这是输出
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() 分隔符。
有没有一种简洁的方法来创建匹配的多行模式列表?
【问题讨论】:
-
我没有看到任何使用外部工具的理由,你为什么不使用 re 模块?
-
公平点,我只是有更多使用 grep、pcgrep 等的经验,而不是使用 re 到 grep 文件。我还认为 pcregrep 可能会对此进行更多优化,并且性能将(最终)成为一个因素。
-
停止梦想表演,并尝试使用语言正则表达式引擎,看看它是否可以完成这项工作,以及执行此操作所需的时间是否可以满足您的需求。之后,并且仅在之后(当您尽一切可能完善您的模式或找到其他语言方式时),尝试使用外部工具。
-
明白了。我通常喜欢在刚开始时考虑性能,所以我可能要做的工作更少,但你说得对,正则表达式机器可能绰绰有余。
标签: python python-2.7 subprocess pcregrep