【问题标题】:How to pass error message from shell script to Python script?如何将错误消息从 shell 脚本传递到 Python 脚本?
【发布时间】:2014-05-28 21:34:00
【问题描述】:

我正在使用 subprocess 模块从 Python 脚本调用 shell 脚本。在我下面的 python 代码中,shell_script 是我的实际脚本。

proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable='/bin/bash')
(stdout, stderr) = proc.communicate()
if proc.returncode != 0:
    print("Errors while executing the shell script: %s" % stderr)
    break

这是我的 shell 脚本,它肯定会失败,因为我故意让它失败,然后我在 shell 脚本上回显这个 echo "Folder doesn't exist on $machine"; 错误,然后以状态 1 退出。

但是,如果您看到我上面的 python 代码,我正在使用stderr 将其打印出来,因此此错误消息不会显示在 Python 脚本端。

for machine in "${MACHINES[@]}"; do
   dircheck=($(ssh -o "StrictHostKeyChecking no" david@${machine} [[ ! -d "$dir3" ]] \&\& exit 1 \; ls -t1 "$dir3"))

   if [[ $? != 0 ]] ;then
       echo "Folder doesn't exist on $machine";
       exit 1
   fi

   if [[ "${dircheck[@]}" = '' ]] ;then
       echo "0 Files on server $machine in $dir3";
       exit 1
   fi
done

知道出了什么问题,我该怎么办?我只是想在出现任何错误时将 shell 脚本上发生的任何错误消息反映到 Python 脚本。

【问题讨论】:

    标签: python linux bash shell subprocess


    【解决方案1】:

    您的 shell 脚本不会写入标准错误,因为 echo 会输出到标准输出。您需要将输出重定向到标准错误,如下所示:

    echo "Folder doesn't exist on $machine" >&2
    

    echo "0 Files on server $machine in $dir3" >&2
    

    【讨论】:

    • 谢谢chepner。在>&2 之后我需要分号吗?意思应该是这样的echo "Folder doesn't exist on $machine" >&2;?
    • 如果您想在同一行添加另一个命令,则只需要分号,例如,echo "..." >&2; exit 1
    • @AKIWEB:如果您希望 shell 脚本的所有输出都转到 stderr;你可以放在顶部:exec >&2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2021-09-20
    • 2016-10-29
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多