Search code examples
pythonunixoperating-systemsubprocessos.system

Python OS and subprocess for grep


I'm trying to execute: grep -A5000 -m1 -e 'dog 123 4335' animals.txt in python script.

Input file:

cat 13123 23424 
deer 2131 213132
bear 2313 21313
dog 123 4335
cat 13123 23424 
deer 2131 213132
bear 2313 21313

Output:

cat 13123 23424 
deer 2131 213132
bear 2313 21313

I tried this command in Unix it works fine. But it's not getting executed using python the OS.system or the subprocess. Please give me the solution for either one.


Solution

  • Use subprocess:

    import subprocess
    
    CMD = "grep -A5000 -m1 -e 'dog 123 4335' animals.txt"
    p = subprocess.run(CMD, shell=True, stdout=subprocess.PIPE)
    print(p.stdout.decode())
    

    Output:

    dog 123 4335
    cat 13123 23424 
    deer 2131 213132
    bear 2313 21313