Using re to perform grep functionality in Python

Chris Angelico rosuav at gmail.com
Wed Mar 1 17:29:17 EST 2017


On Thu, Mar 2, 2017 at 8:55 AM,  <robert at forzasilicon.com> wrote:
> Hi All,
>
> I'm relatively new to Python, and I am having some trouble with one of my scripts. Basically, this script connects to a server via ssh, runs Dell's omreport output, and then externally pipes it to a mail script in cron. The script uses an external call to grep via subprocess, but I would like to internalize everything to run in Python. I've read that re can accomplish the filtering, but I am having trouble getting it to duplicate what I already have.
>
> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
> if call(["grep", "-i", "ID"], stdin=p.stdout) != 0:

This means "filter for lines that contain ID, case insensitively".

> for line in p.stdout:
>         final = re.findall('ID', line, re.DOTALL)
>         print final
> p.wait()

This part doesn't have the case sensitivity flag set.

But if this is the only thing you're doing with grep, you don't need a
regex at all. You can simply check if "ID" exists in the string. Since
you're using Python 2, I'm going to assume a naive byte-based case
insensitivity is sufficient for you, as you're probably working with
English-only and ASCII-only here.

for line in p.stdout:
    if "ID" in line.upper():
        print(line)
p.wait()

Give that a try :)

Oh, and if case insensitivity isn't an issue to you (if you don't
actually want "fluid" to show up), you can remove the .upper and just
write:

    if "ID" in line:

Very clean and pretty, IMO.

ChrisA


More information about the Python-list mailing list