【问题标题】:How to kill python script with bash script如何用 bash 脚本杀死 python 脚本
【发布时间】:2017-03-31 20:54:12
【问题描述】:

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

请帮忙,谢谢!

【问题讨论】:

  • 你在ps的进程信息中找到关键字“test.py”了吗?

标签: python linux bash raspberry-pi3


【解决方案1】:

使用pkill 命令作为

pkill -f test.py

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

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

或者,如果识别出多个正在运行的程序实例并且需要全部终止,则在 Linux 和 BSD 上使用 killall(1)

killall test.py 

【讨论】:

  • 如果您运行同一脚本的多个实例,这将不起作用。
  • 太棒了!杀死所有脚本实例的好解决方案
  • 在 linux 的后台运行多个 python 进程就像一个冠军。我从未使用过 pkill,但它肯定比 kill 或 killall 更容易。不错
【解决方案2】:

您可以使用! 获取最后一条命令的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 之类的命令可能会有风险。

【讨论】:

    【解决方案3】:
    ps -ef | grep python
    

    它会返回“pid”然后杀死进程

    sudo kill -9 pid
    

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

    【讨论】:

    • kill -9 命令的行为与kill 不同。使用-9 选项时要注意。
    【解决方案4】:

    使用 bashisms。

    #!/bin/bash
    
    python test.py &
    kill $!
    

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

    【讨论】:

      【解决方案5】:
      killall python3
      

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

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 2021-05-02
        • 1970-01-01
        • 2016-01-24
        • 1970-01-01
        • 2017-11-13
        • 1970-01-01
        • 2015-12-22
        • 2015-10-05
        相关资源
        最近更新 更多