【问题标题】:Inside subprocess.run(..., check=True), how to prevent a failed command from exiting with a non-zero status?在 subprocess.run(..., check=True) 内部,如何防止失败的命令以非零状态退出?
【发布时间】:2021-12-21 20:04:41
【问题描述】:

我希望通过以下代码:

import subprocess
subprocess.run("pkill -f non_existent_process_name || true", shell=True, check=True)

但是,它总是出错:

subprocess.CalledProcessError: 命令'pkill -f non_existent_process_name || true' 死于

这是为什么呢?我怎样才能做到这一点?

在普通终端 shell 中,运行(pkill -f non_existent_process_name || true); echo $? 显示 0,这意味着括号中的部分按预期以 0 退出。

【问题讨论】:

    标签: python python-3.x bash subprocess


    【解决方案1】:

    您获得SIGTERM 的原因是您无意中杀死了正在运行pkill 的shell。

    当您使用 shell=True 运行命令时,它会将该命令作为 shell 的参数运行,如下所示:

    /bin/sh -c 'pkill -f non_existent_process_name || true'
    

    由于non_existent_process_name/bin/sh 命令行的一部分,所以shell 被终止。

    根据您要匹配的具体流程,您需要尝试pkill 的选项。删除 -f 或添加 -x 可能会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-28
      • 2020-10-25
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多