Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store value of os.system or os.popen

I want to grep the error's out of a log file and save the value as an error. When I use:

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

I get the return code that the command worked or not. When I use:

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

I get what the command is trying to do.

When I run this in the command line I get 3 as thats how many errors there are.

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

Thanks

like image 319
chrisg Avatar asked Jan 23 '23 02:01

chrisg


1 Answers

popen is deprecated. 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]
like image 200
Olivier Verdier Avatar answered Jan 31 '23 14:01

Olivier Verdier