Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python shell脚本来监视一个";字;在日志中,然后终止并重新启动进程_Python_Linux_Shell - Fatal编程技术网

Python shell脚本来监视一个";字;在日志中,然后终止并重新启动进程

Python shell脚本来监视一个";字;在日志中,然后终止并重新启动进程,python,linux,shell,Python,Linux,Shell,我对script/linux还不熟悉。我一直在做一些研究,但现在我被卡住了 我运行了一个python脚本,在某个时候我遇到了一个错误(显示在终端窗口中) 我需要: 1.将显示的内容放入日志或txt文件中, 2.监视该文件,当“331”一词出现时: 3.终止script.py进程 4.重新启动它(保持循环,这样每次出现“331”错误时它都会终止并重新启动script.py 在我无知的情况下,我这样做了: #!/bin/sh #execute the python script as a norma

我对script/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

你的循环在哪里?
tail-f
永远不会退出,所以脚本无论如何都会被卡住。而且
killall main.py
不会工作,因为进程将被称为
python
-
killall python
可能不是一个好主意。哦,脚本将挂起
python main.py
,因为它正在运行在前台。可以尝试执行
tail-f…| grep“331”| head-n 1
,应该暂停,直到它在日志中找到这样一行。感谢您的回复!因此,只需将tail命令更改为您建议的命令就可以了?我需要在后台运行python脚本吗?如果需要,我该怎么做?我对*nix和脚本编写非常陌生,请原谅我的无知。我建议首先尝试我的答案,but:在后台运行python脚本:
python main.py&
。更改命令可能会起作用,但您仍然需要一个循环,并且不需要条件。好的,运行python main.py | tee output.txt怎么样?应该是python main.py&| tee output.txt才能使其在后台运行?只是一个问题:是否可以使用“直到”循环以监视commnad输出状态(0或1),并在输出值与0不同时重新启动脚本?您是指程序的返回值吗?当然。这在
$?
中。