繁体   English   中英

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

[英]How to pass error message from shell script to Python script?

我使用子进程模块从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脚本失败肯定,因为我故意让它失败然后我回应出这个echo "Folder doesn't exist on $machine"; shell脚本上的错误,然后退出状态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脚本上发生的任何事情上。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM