Home > Software design >  Python OS and subprocess for grep
Python OS and subprocess for grep

Time:07-07

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.

CodePudding user response:

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
  • Related