如何将错误消息从shell脚本传递到Python脚本?

时间:2014-04-14 19:12:00

标签: python linux bash shell 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脚本端,因为如果你看到我上面的python代码,我会使用stderr将它打印出来。

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脚本上发生的任何错误消息。

1 个答案:

答案 0 :(得分:3)

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

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

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