如何用 bash 脚本杀死 python 脚本

How to kill python script with bash script

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

#!/bin/bash

python test.py &

那么我怎样才能用 bash 脚本终止脚本呢?

我用下面的命令kill但是输出了no process found

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

我尝试通过 ps aux | less 检查 运行ning 进程,发现 运行ning 脚本具有 python test.py

命令

请帮忙,谢谢!

使用pkill命令作为

pkill -f test.py

(或)使用 pgrep 搜索实际进程 ID

的更简单的方法
kill $(pgrep -f 'python test.py')

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

上使用 killall(1)
killall test.py 

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

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

#!/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 之类的命令可能存在风险。

ps -ef | grep python

它将 return "pid" 然后通过

终止进程
sudo kill -9 pid

例如 ps 命令的输出: user 13035 4729 0 13:44 pts/10 00:00:00 python (这里13035是pid)

使用 bashisms。

#!/bin/bash

python test.py &
kill $!

$! 是在后台启动的最后一个进程的 PID。如果在后台启动多个脚本,也可以将其保存在另一个变量中。

killall python3

将中断 所有 python3 脚本 运行.