2

我试图在打印此列表时删除评论。

我在用

output = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
for item in output:
    print item

这非常适合给我整个文件,但是打印时如何删除注释?

由于文件的位置,我必须使用 cat 来获取文件。

4

4 回答 4

2

您可以使用正则表达式re模块来识别注释,然后在脚本中删除它们或忽略它们。

于 2013-07-15T09:01:47.897 回答
2

该函数self.cluster.execCmdVerify显然返回一个iterable,所以你可以简单地这样做:

import re

def remove_comments(line):
    """Return empty string if line begins with #."""
    return re.sub(re.compile("#.*?\n" ) ,"" ,line)
    return line

data = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')

for line in data:
    print remove_comments(line)

以下示例用于字符串输出:

为了灵活起见,您可以从一个字符串创建一个类似文件的对象(只要它是一个字符串)

from cStringIO import StringIO
import re

def remove_comments(line):
    """Return empty string if line begins with #."""
    return re.sub(re.compile("#.*?\n" ) ,"" ,line)
    return line

data = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
data_file = StringIO(data)

while True:
    line = data_file.read()
    print remove_comments(line)
    if len(line) == 0:
        break

或者只是remove_comments()在你的for-loop.

于 2013-07-15T09:05:46.250 回答
0

greping 输出怎么样

grep -v '#' /opt/tpd/node_test/unit_test_list
于 2013-07-15T09:02:36.720 回答
0

例如,如果它用于 python 文件,并且您想删除以 # 开头的行,您可以尝试:

cat yourfile | grep -v '#'

编辑:

如果你不需要猫,你可以直接做:

grep -v "#" yourfile
于 2013-07-15T09:02:59.350 回答