简体   繁体   中英

Search for line in string Python

I try to check for every line in a file if it's in another string (output of a command that I executed). It prints me "not good" every time... Can anyone see what is wrong?

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"

You may need to strip the newline if you are looking for a substring:

 if line.rstrip() in out

You can also use check_output to get the output and pass a list of args:

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

You should also use with to open your files:

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

You may be getting output from stderr so you should also verify in your own code that out actually contains anything and it is not just an empty string.

If you are looking for an exact line match make out a set of lines and you have verified or corrected to get output:

st = set(out.splitlines())

If you are looking for a substring a newline will mean the check can fail:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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