在字符串 Python 中搜索行
Search for line in string Python
我尝试检查文件中的每一行是否在另一个字符串中(我执行的命令的输出)。
它每次都打印我 "not good" ...
谁能看出哪里出了问题?
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
获取输出并传递参数列表:
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
我尝试检查文件中的每一行是否在另一个字符串中(我执行的命令的输出)。 它每次都打印我 "not good" ... 谁能看出哪里出了问题?
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
获取输出并传递参数列表:
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