如何使用bash脚本杀死python脚本

时间:2016-11-17 10:45:36

标签: python linux bash raspberry-pi3

我运行一个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

请帮助,谢谢!

5 个答案:

答案 0 :(得分:15)

使用pkill命令作为

pkill -f test.py

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

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

答案 1 :(得分:1)

您可以使用!获取最后一个命令的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这样的命令或者对ps aux的追问可能会有风险。

答案 2 :(得分:0)

ps -ef | grep python

它将返回“pid”然后通过

终止进程
sudo kill -9 pid

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

答案 3 :(得分:0)

使用bashisms。

$!

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

答案 4 :(得分:0)

killall python3

将中断任何和所有 python3 脚本的运行。

相关问题