pgrep -f myprogram.py 如果进程未运行则不返回任何内容

问题描述 投票:0回答:2

Ubuntu 18.04、Python 3

我正在尝试重新启动我的 python 脚本,以防它停止。我正在使用本文的第二个响应:https://unix.stackexchange.com/questions/107939/how-to-restart-the-python-script-automatically-if-it-is-killed-or-死了

我创建了一个 cron 作业,如果我放入一些我知道会失败的虚假内容,它就会启动我的 python 脚本。但是,当使用 pgrep 检查它何时运行时,我的 python 脚本将不会运行。

cron 作业是:

pgrep -f myprogram.py || nohup python /home/User/myprogram.py &  > myprogram.out

如果我通过命令行正常启动 python 脚本,pgrep 会正确返回 PID。当它不运行时,pgrep 不会返回任何内容。

我相信我的 cron 作业设置正确,但如果脚本未运行,pgrep 不会返回“1 或 0”响应来启动脚本。

如果我的脚本运行 not 使 cron 作业能够识别并启动我的 python 脚本,如何让 pgrep 返回一个值?

python ubuntu grep restart autostart
2个回答
0
投票

这可以很容易解决:

pgrep -f myprogram.py ... | wc -l

程序运行时,只有一个结果,因此

wc -l
给出 1。
当你的程序没有运行时,没有结果,所以
wc -l
给出 0。


0
投票

得到同样的。

pgrep -f
很棘手,因为它将匹配整个命令,而不仅仅是进程名称。这当然是所希望的,但需要额外小心。具体来说,它也会匹配... crontab 调用自身:) 当 cron 运行作业时,它会以
sh -c "<your task definition>"
的方式运行它。您可以通过在 pgrep 调用中添加
-a
来轻松检查它 - 然后在从 cron 收到的邮件中您应该看到匹配的进程。 您还可以通过将“任务定义”包装在
sh -c
中从控制台进行检查。 您可以使用
-x
标志来修复它 - 然后它会完全匹配给定的模式。所以在你的情况下:

pgrep -fx "nohup python /home/User/myprogram.py" || nohup python /home/User/myprogram.py &  > myprogram.out

应该可以工作

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.