Check if a unix command returns nothing

Question:

I am trying to see if myfile returns nothing after a grep from within python, something like this:

command="cat my_file.txt | grep 'string_to_find'"

if os.system(command) == '':
   print('nothing found')
Asked By: curious

||

Answers:

Converting comment to answer:

command="cat my_file.txt | grep 'string_to_find'"

if os.popen(command).read() == '':
   print('nothing found')

Documentation for os.popen()

Answered By: user56700

another solution:

import os

command="cat my_file.txt | grep 'string_to_find'"

if os.system(command):
    print('nothing found')
else:
    print('something found')
Answered By: Daniel Ben-Shabtay

Grep’s exit code is 0 if a match was found and 1 if no match was found. (Errors, for example in the regular expression, produce exit code 2). On Posix systems (including Linux), os.system returns 256 times the exit code if the command ran to completion, or the number of the signal which terminated the command if it was killed by a signal. (I think it’s different on Windows. Consult the Python docs if that matters to you.)

So a crude solution would be:

if os.system("grep 'string to find' 'my_file.txt'") == 256:
    # Nothing found

# Or even
if os.system("grep 'string to find' 'my_file.txt'") != 0:
    # Nothing found or some error occurred

Either way, all output goes to stdout and error messages to stderr, which are generally the user’s terminal. If you just want to know if the pattern matches somewhere in the file, use grep -q, which suppresses errors and output and stops at the first match (which can be quite a lot faster if there are large files and the pattern usually occurs near the beginning.) (Shell errors will still be reported on stderr, though.)

If you need to do a better analysis of error conditions (bad regex, file not found, bad shell command format, etc.), then you’ll probably want to use an interface which can capture stderr, such as subprocess.Popen.

Answered By: rici
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.