【问题标题】:Search for line in string Python在字符串 Python 中搜索行
【发布时间】:2015-05-28 04:06:05
【问题描述】:

我尝试检查文件中的每一行是否在另一个字符串中(我执行的命令的输出)。 它每次都打印我“不好”... 任何人都可以看出什么问题吗?

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"

【问题讨论】:

    标签: python string file search line


    【解决方案1】:

    如果您正在寻找子字符串,您可能需要去掉换行符:

     if line.rstrip() in out
    

    您也可以使用check_output 来获取输出并传递参数列表:

    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")
    

    您可能会从 stderr 获取输出,因此您还应该在自己的代码中验证 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2015-12-25
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      相关资源
      最近更新 更多