The recipe below passes a filename and an argument to grep, returning the stdout and stderr. Each line in the stdout will have its line number prepended.
1 2 3 4 5 6
import subprocess def grep(filename, arg): process = subprocess.Popen(['grep', '-n', arg, filename], stdout=subprocess.PIPE) stdout, stderr = process.communicate() return stdout, stderr
Reading a subset of a text file is a common task. There are many ways of approaching the problem but none as simple as reusing existing tools. Grep is an excellent candidate as it is fast, efficient, and offers great flexibility in selecting the desired content.