![](/img/trans.png)
[英]How do I go from a bash script that calls a python script to a python script calling a bash script?
[英]How do i halt execution of bash script when a python script fails?
所以我的 shell 脚本中有以下内容:
python get_link.py $password | wget --content-disposition -i-
mkdir web_folder
mv *.zip web_folder
所以第一行是执行我编写的 python 脚本,它打印出一个网站链接,然后wget 立即检索 python 脚本返回的链接并下载 zip 文件。
第二行创建一个名为“web_folder”的新文件夹,第三行将 wget 下载的 zip 文件移动到“web_folder”中
我面临的问题是,如果 python 脚本由于 $password 密码错误等错误而失败,则 shell 脚本命令的 rest 仍在执行。 在我的情况下,打印以下内容:
mv: cannot stat ‘*.zip’: No such file or directory
即使 python 脚本失败,mkdir 和 mv 命令仍然会执行。 当 python 脚本失败时,如何确保脚本完全停止?
如果您使用的是 bash,请查看 PIPESTATUS 变量。 ${PIPESTATUS[0]} 将具有来自第一个 pipe 的返回码。
#!/bin/bash
python get_link.py $password | wget --content-disposition -i-
if [ ${PIPESTATUS[0]} -eq 0 ]
then
echo "python get_link.py successful code here"
else
echo "python get_link.py failed code here"
fi
一个紧凑的解决方案,用 and 链接一切:
(python get_link.py $password | wget --content-disposition -i-) && (mkdir web_folder) && (mv *.zip web_folder)
不太紧凑的解决方案:
python get_link.py $password | wget --content-disposition -i-
if [ $? -eq 0 ]; then
mkdir web_folder
mv *.zip web_folder
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.