我有一个shell脚本,我在其中调用python脚本说new.py:
#!/usr/bin/ksh
python new.py
Run Code Online (Sandbox Code Playgroud)
现在这new.py就像 -
if not os.path.exists('/tmp/filename'):
print "file does not exist"
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
如果文件没有退出,则python脚本返回但shell脚本继续执行.如果文件没有退出并且我的python脚本退出,我希望shell脚本也停止在那一点.
请建议如何捕获shell脚本中的返回以进一步停止执行.
您需要从exit函数返回除零之外的其他内容.
if os.path.exists("/tmp/filename"):
sys.exit(0)
else:
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
错误值仅为8位,因此只有整数的低8位返回给shell.如果提供负数,则将返回二进制补码表示的低8位,这可能不是您想要的.您通常不会返回负数.
if ! python new.py
then
echo "Script failed"
exit
fi
Run Code Online (Sandbox Code Playgroud)
这假设Python脚本使用sys.exit(0)时,你的shell脚本应该继续和sys.exit(1)(或其他非零值)时,应立即停止(这是习惯,当出现错误时返回一个非零的退出代码).