开发者

Python subprocess to call Unix commands, a question about how output is stored

I am writing a python script that reads a line/string, calls Unix, uses grep to search a query file for lines that contain the string, and then prints the results.

from subprocess import call

for line in infilelines:

    output = call(["grep", line, "path/to/query/file"])
    print output
    print line`

When I look at my results printed to the screen, I will get a list of matching strings from the query file, but I will also get "1" and "0" integers as output, and line is never printed to the scr开发者_如何学Goeen. I expect to get the lines from the query file that match my string, followed by the string that I used in my search.


call returns the process return code.

If using Python 2.7, use check_output.

from subprocess import check_output
output = check_output(["grep", line, "path/to/query/file"])

If using anything before that, use communicate.

import subprocess
process = subprocess.Popen(["grep", line, "path/to/query/file"], stdout=subprocess.PIPE)
output = process.communicate()[0]

This will open a pipe for stdout that you can read with communicate. If you want stderr too, you need to add "stderr=subprocess.PIPE" too.

This will return the full output. If you want to parse it into separate lines, use split.

output.split('\n')

I believe Python takes care of line-ending conversions for you, but since you're using grep I'm going to assume you're on Unix where the line-ending is \n anyway.

http://docs.python.org/library/subprocess.html#subprocess.check_output


The following code works with Python >= 2.5:

from commands import getoutput
output = getoutput('grep %s path/to/query/file' % line)
output_list = output.splitlines()


Why would you want to execute a call to external grep when Python itself can do it? This is extra overhead and your code will then be dependent on grep being installed. This is how you do simple grep in Python with "in" operator.

query=open("/path/to/query/file").readlines()
query=[ i.rstrip() for i in query ]
f=open("file")
for line in f:
    if "line" in query:
        print line.rstrip()
f.close()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜