Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect subprocess.run output to file

I've seen a lot of other pages here that talk output grep output to a file but I can't seem to make any of those work.

I have

subprocess.run(['grep', '-o', searchFor, filename])

if this wasn't a subprocess I would use something like

grep -o searchfor filename >> outputfile.txt

and when I try to use > or >> or anything else in the subprocess, I can't get it to output to a simple txt file. I assume that this is because most all of the pages I've seen here are writing to a file from regular command compared to me trying within the subprocess. My guess is that my syntax is wrong. Where should > or >> or whatever I should be using go? I've tried after the ] and before and many other combinations.

like image 303
contactme8359 Avatar asked Nov 04 '25 16:11

contactme8359


1 Answers

Open the file in write (>) or append (>>) mode, and assign the descriptor associated with it to stdout in subprocess.run call.

with open('outputfile.txt', 'w') as fd:
  subprocess.run(['grep', '-o', searchFor, filename], stdout=fd)
like image 119
oguz ismail Avatar answered Nov 06 '25 08:11

oguz ismail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!