Consider the following examples –
Python 2.4.3 (#1, Jan 14 2011, 00:20:04)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("grep -i beatles blur.txt")
Blur's debut album Leisure (1991) incorporated the sounds of Madchester and shoegazing. Following a stylistic change.influenced by English guitar pop groups such as The Kinks, The Beatles and XTC.
0
>>> os.system("grep -i metallica blur.txt")
256
>>>
So, in this case, I don’t want the line having my searched keyword to be printed on the Python shell, I just want the return value i.e. 0 if keyword is present and non-zero if its not. How to achieve that?
You just need to use
-qkey of thegrep:I must note that
-qis not portable key of thegrep, it will work only with GNU grep (Linux and so on).When you want to make it work on all systems, you must use
popen/subprocess.Popenand redirections of streams.