无法对运行 Python 脚本的 Bash 脚本使用“停止”命令

阿拉斯代尔

我有一个 bash 脚本,它调用一个我想在后台连续运行的 Python 脚本。我可以启动 bash 脚本,并且 Python 脚本运行,但是我无法使用带有 bash 脚本的“停止”命令来停止它。

这是 bash 脚本:

#!/bin/bash

 case $1 in
    start)
       echo 'Running test.py'
       exec 2>&1 /opt/anaconda3/envs/my_env/bin/python /home/my_name/scripts/test.py &
       echo 'Assigning pid'
       echo $! > /home/my_name/scripts/test.pid;;
     stop)
       kill 'cat /home/my_name/scripts/test.pid';;
       
     *)
       echo "usage: "$1" {start|stop}" ;;
 esac
 exit 0

这是 Python 脚本:

import time
from pathlib import Path

count = 0 
while True:
    with open(Path(__file__).parent.resolve() / "test.txt", 'a') as f:
        f.write(str(count))
    count += 1
    time.sleep(1)

Python 代码运行良好,因此不值得过多讨论。它只是每秒将一个整数写入文本文件,每次递增 1。

这是我在命令行上从包含 Python 和 bash 脚本的文件夹中得到的内容:

$ sudo ./test.sh start
Running test.py
Assigning pid
$ sudo ./test.sh stop
./test.sh: line 10: kill: cat /home/my_name/scripts/test.pid: arguments must be process or job IDs
$ ps -aux | grep test
root      91366  0.1  0.0  26704  9320 pts/6    S    19:39   0:00 /opt/anaconda3/envs/my_env/bin/python /home/my_name/scripts/test.py
VEIC\da+  92004  0.0  0.0  14436  1012 pts/11   S+   19:41   0:00 grep --color=auto test
$ cat test.pid
91366

因此,您可以看到写入 pid 文件的 pidtest.pid与命令中显示的 pid匹配ps -aux | grep test但是当我尝试stop在 bash 脚本中使用该命令时,我被告知 pid 文件的内容不是进程或作业 ID。

我最终希望将它与 Monit 结合使用,但在我这样做之前需要克服这个 bash 脚本的困难。任何帮助将不胜感激!

jsbillings
  kill 'cat /home/my_name/scripts/test.pid';;

你可能希望它是:

  kill `cat /home/my_name/scripts/test.pid`;;

(反引号代替单引号)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章