Store os.system or os.popen value

I want to remove the error from the log file and save the value as an error. When i use:

errors = os.system("cat log.txt | grep 'ERROR' | wc -l")

I get a return code that the team worked or not. When i use:

errors = os.popen("cat log.txt | grep 'ERROR' | wc -l")

I get what the command is trying to execute.

When I run this on the command line, I get 3 because this is the number of errors.

Can anyone suggest another way in Python that will allow me to save the value of this bash command?

thank

+3
source share
4 answers

popenoutdated. Use subprocess instead . For example, in your case:

p1 = Popen(["cat", "log.txt"], stdout=PIPE)
p2 = Popen(["grep", "ERROR"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
+6
source

You are probably looking for:

grep -c 'ERROR' log.txt

subprocess. , , .

+1

, popen, .

p = os.popen("cat log.txt | grep 'ERROR' | wc -l")

:

output = p.readline()

, , .

EDIT: , , Python 2.6 os.popen . , , . . , .

+1

'ERROR' :

nerrors = open('log.txt').read().count('ERROR') # put whole file in memory

, 'ERROR':

nerrors = sum(1 for line in open('log.txt') if 'ERROR' in line) # line at a time

bash, Python 2.7 +:

from subprocess import check_output as qx
nerrors = int(qx("cat your_file.txt | grep 'ERROR' | wc -l", shell=True))

. check_output() Python < 2.7.

0

Source: https://habr.com/ru/post/1745073/


All Articles