繁体   English   中英

在字符串Python中搜索行

[英]Search for line in string Python

我尝试检查文件中的每一行是否在另一个字符串中(我执行的命令的输出)。 每次都会打印出“不好”的字样……有人看到错了吗?

connections = subprocess.Popen(["vol connscan"], stdout=subprocess.PIPE, shell=True)
(out, err) = connections.communicate()  
file = open('/opt/hila','r')
    for line in file:
        if line in out:
            print "good"
        else:
            print "not good"

如果要查找子字符串,则可能需要删除换行符:

 if line.rstrip() in out

您还可以使用check_output获取输出并传递args列表:

out = subprocess.check_output(["vol", "connscan"])

您还应该使用with打开文件:

out = subprocess.check_output(["vol","connscan"])
with  open('/opt/hila') as f:
    for line in f:
        if line.rstrip() in out:
            print("good")
        else:
            print("bad")

你可能会得到从标准错误输出,所以你也应该在自己的代码验证out实际上包含任何东西,它不只是一个空字符串。

如果您正在寻找精确的行匹配,请out一组行,并且已经过验证或更正以获取输出:

st = set(out.splitlines())

如果您正在寻找一个子字符串,换行符将意味着检查可能失败:

In [2]: line = "foo\n"

In [3]: out = "foo bar"

In [4]: line in out
Out[4]: False

In [5]: line.rstrip() in out
Out[5]: True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM