gpt4 book ai didi

python - shell脚本监视日志中的 "word",然后终止并重新启动进程

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:05 26 4
gpt4 key购买 nike

我是脚本/Linux 的新手。我一直在为此做一些研究,但现在我被卡住了。

我运行了一个 python 脚本,但在一段时间后出现错误(显示在终端窗口中)。

我需要:1.将显示的内容放入日志或txt文件中,2. 监控该文件,当出现“331”字样时:3.杀死script.py进程4. 重新启动它(保持这个循环,所以它会在每次出现“331”错误时终止并重新启动 script.py。

在我的无知中,我这样做了:

#!/bin/sh
#execute the python script as a normal user and make a output.txt file so the grep command can find the "331" word

echo "Starting Script"
python main.py | tee output.txt

#using tail and grep to look for the "331" word:
if [ tail -f /path/to/script/output.txt | grep "331" ]; then
echo "Error found. Killing Process"
killall main.py
echo "Restarting script..."
./startcap2.sh
fi
done

它启动脚本,但如果出现错误则无法终止/重启。

我错过了什么?

感谢您的帮助!

最佳答案

如果您只是对进程本身进行 grep,并使用 head -n 1,它应该会因管道损坏而自动终止:

#!/bin/sh

echo "Starting Script"
while true
do
python main.py | tee -a output.txt | grep "331" | head -n 1 # run until first line with 331 occurs
echo "Restarting script..."
done

关于python - shell脚本监视日志中的 "word",然后终止并重新启动进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40706952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com