如何用 bash 脚本杀死 python 脚本

新手上路,请多包涵

我运行一个 bash 脚本,启动一个 python 脚本在后台运行

#!/bin/bash

python test.py &

那么我怎样才能用 bash 脚本杀死脚本呢?

我使用以下命令杀死但输出 no process found

 killall $(ps aux | grep test.py | grep -v grep | awk '{ print $1 }')

我尝试通过 ps aux | less 检查正在运行的进程,发现运行脚本的命令为 python test.py

请帮忙,谢谢!

原文由 Jeff Pang 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 580
2 个回答

使用 pkill 命令作为

pkill -f test.py

(或)更简单的方法使用 pgrep 来搜索实际的进程 ID

 kill $(pgrep -f 'python test.py')

或者,如果识别出多个正在运行的程序实例并且需要杀死所有这些实例,请在 Linux 和 BSD 上使用 killall(1)

 killall test.py

原文由 Inian 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 ! 获取最后一个命令的 PID。

我会建议类似于以下内容,同时检查您要运行的进程是否已经在运行:

 #!/bin/bash

if [[ ! -e /tmp/test.py.pid ]]; then   # Check if the file already exists
    python test.py &                   #+and if so do not run another process.
    echo $! > /tmp/test.py.pid
else
    echo -n "ERROR: The process is already running with pid "
    cat /tmp/test.py.pid
    echo
fi

然后,当你想杀死它时:

 #!/bin/bash

if [[ -e /tmp/test.py.pid ]]; then   # If the file do not exists, then the
    kill `cat /tmp/test.py.pid`      #+the process is not running. Useless
    rm /tmp/test.py.pid              #+trying to kill it.
else
    echo "test.py is not running"
fi

当然,如果杀戮必须在命令启动后的某个时间发生,您可以将所有内容放在同一个脚本中:

 #!/bin/bash

python test.py &                    # This does not check if the command
echo $! > /tmp/test.py.pid          #+has already been executed. But,
                                    #+would have problems if more than 1
sleep(<number_of_seconds_to_wait>)  #+have been started since the pid file would.
                                    #+be overwritten.
if [[ -e /tmp/test.py.pid ]]; then
    kill `cat /tmp/test.py.pid`
else
    echo "test.py is not running"
fi

如果您希望能够同时运行更多具有相同名称的命令并能够有选择地杀死它们,则需要对脚本进行小的编辑。告诉我,我会尽力帮助你!

有了这样的东西,你确定你正在杀死你想杀死的东西。像 pkill 或 grepping ps aux 这样的命令可能有风险。

原文由 Riccardo Petraglia 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题