I have a server-like app I want to run from Python. It never stops until user interrupts it. I want to continuously redirect both stdout and stderr to parent when the app runs. Lucklily, that's exactly what subprocess.run
does.
Shell:
$ my-app
1
2
3
...
wrapper.py
:
import subprocess
subprocess.run(['my-app'])
Executing wrapper.py
:
$ python wrapper.py
1
2
3
...
I believe it's thanks to the fact that subprocess.run
inherits stdout and stderr file descriptiors from the parent process. Good.
But now I need to do something when the app outputs particular line. Imagine I want to run arbitrary Python code when the output line will contain 4
:
$ python wrapper.py
1
2
3
4 <-- here I want to do something
...
Or I want to remove some lines from the output:
$ python wrapper.py <-- allowed only odd numbers
1
3
...
I thought I could have a filtering function which I'll just hook somehow into the subprocess.run
and it will get called with every line of the output, regardless whether it's stdout or stderr:
def filter_fn(line):
if line ...:
return line.replace(...
...
But how to achieve this? How to hook such or similar function into the subprocess.run
call?
Note: I can't use the sh
library as it has zero support for Windows.