如何将错误信息从shell脚本传递给Python脚本?

1 投票
1 回答
1009 浏览
提问于 2025-04-18 02:43

我在用Python脚本调用一个shell脚本,使用的是subprocess模块。在我下面的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脚本中发生的错误信息反映到Python脚本里,无论发生什么错误。

1 个回答

3

你的脚本没有写入标准错误,因为echo命令是输出到标准输出的。你需要把输出重定向到标准错误,方法如下:

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

还有

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

撰写回答