theharshest
theharshest

Reputation: 7867

How to skip printing the command output and just get the return value from a os.system command?

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?

Upvotes: 2

Views: 1626

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208485

For the generic question of "how do I prevent os.system() output from being printed", the best way to do this is to use the subprocess module, which is the recommended way to run external programs and it provides straightforward output redirection.

Here is how this might look for your example:

import os
import subprocess

devnull = open(os.devnull, 'wb')
subprocess.call('grep -i beatles blur.txt', stdout=devnull, stderr=devnull, shell=True)

The shell=True option means that that the program will be executed through the shell, which is what os.system() does, but it is better (safer) to drop the shell=True and pass a list with the command arguments.

subprocess.call(['grep', '-i', 'beatles', 'blur.txt'], stdout=devnull, stderr=devnull)

Upvotes: 1

Igor Chubin
Igor Chubin

Reputation: 64563

You just need to use -q key of the grep:

$ python
Python 2.7.3rc2 (default, Apr  5 2012, 18:58:12) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("grep -iq igor /etc/passwd")
0
>>> os.system("grep -iq oleg /etc/passwd")
256
>>> 

I must note that -q is not portable key of the grep, 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.Popen and redirections of streams.

>>> import subprocess
>>> null = open(os.devnull, "w")
>>> grep = subprocess.Popen(shlex.split("grep -i oleg /etc/passwd"), stderr = null, stdout = null)
>>> grep.communicate()
(None, None)
>>> print grep.returncode
1
>>> grep = subprocess.Popen(shlex.split("grep -i igor /etc/passwd"), stderr = null, stdout = null)
>>> grep.communicate()
(None, None)
>>> print grep.returncode
0

Upvotes: 4

the paul
the paul

Reputation: 9161

Igor Chubin's answer is a good one, but the simplest answer in your case may be just to redirect the output via the shell (since os.system is going to invoke a shell anyway, you may as well use it.)

os.system("grep -i beatles blur.txt > /dev/null 2>&1")

Upvotes: 1

Related Questions