Hi I want to run the python code and logging output also want to when output contain specific string and kill the process
I knew the command that "run python code and logging output"
python run.py 2>&1 | tee output.log
but I don't know how to grep the specific string and kill the process.
CodePudding user response:
The best solution would be to modify run.py
accordingly. If this is not an option, the closest you can get is using the -m
option of grep
:
python run.py 2>&1 | tee output.log | grep -m 1 YOUR_PATTERN
After grep
gets the first match, it will exit and with this close the pipe to tee
. After that pipe is closed, tee will eventually (i.e. the next time it is time to flush its output buffer) detect that the output pipe is gone and exit, and with this close the pipe to python
. When run.py
is flushing its output buffer, it detects that the pipe is gone and terminate. Due to this buffering and parallelism of the three processes, it takes some time between grep
finding the pattern and python
actually terminating itself.
CodePudding user response:
I mean I usually just used this:
proxy() {
while read -r line; do
if echo "$line" | grep -q "$1"; then
kill -9 "$PID_OF_BSH"
else
echo "$line"
fi
done
}
main() {
bash b.sh | proxy 1
}
main "$@"
b.sh:
main() {
while true; do
echo "$((RANDOM % 16))"
done
}
main "$@"
Sorry, this answer is not full as I rlly forgot how to get the PID of it :)