2016-11-17 149 views
1

Python脚本我运行与开始一个python脚本在后台运行bash脚本如何杀死bash脚本

#!/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

运行有命令脚本,请帮助,谢谢!

+0

您是否在'ps'的进程信息中找到了关键字“test.py”? – staticor

回答

6

使用pkill命令

pkill -f test.py 

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

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

在脚本中使用'pkill'实际上非常危险,因为你会杀死所有名为参数的进程! –

+0

另一个盲人在中途? – Inian

+0

@RiccardoPetraglia:这个更新对你来说足够好吗? – Inian

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或grey ps aux的命令可能有风险。

0
ps -ef | grep python 

它将返回 “PID”,则终止该进程通过

sudo kill -9 pid 

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

+0

'kill -9'命令与'kill'有不同的行为。使用'-9'选项时请注意。 –

0

随着bashisms的使用。

#!/bin/bash 

python test.py & 
kill $! 

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