[英]exit python script if get an error while get and exit from subprocess
我目前正在使用python脚本,而python脚本又在两者之间调用Shell脚本。 要求是,在执行Shell脚本期间,如果发现任何错误,则必须退出Shell脚本以及触发该脚本的python脚本。
下面是代码片段:
if re.match('(.+)' + text + '(.+)', line):
output=subprocess.Popen(['sh', 'stest.bash'], stdout=subprocess.PIPE).communicate()[0]
elif re.match('(.+)' + text1 + '(.+)', line):
output=subprocess.Popen(['sh', '1.bash'], stdout=subprocess.PIPE).communicate()[0]
****---here if i get error in 1.bash script then i wants to stop the whole execution****
else:
print("something went wrong!Please look into")
以下是bash脚本:
if [soemthing]
then
echo "something"
else
echo "exit" exit
fi
当上述脚本运行失败后,python脚本将无法正确退出。 有人可以指出要修改哪些内容以修正它吗?
如果可以使用异常退出,则将代码更改为使用run
:
if re.match('(.+)' + text + '(.+)', line):
subprocess.run(['sh', 'stest.bash'], check=True)
elif re.match('(.+)' + text1 + '(.+)', line):
subprocess.run(['sh', '1.bash'], check=True)
else:
print("something went wrong!Please look into")
如果您需要退出并返回代码0:
if re.match('(.+)' + text + '(.+)', line):
return_code = subprocess.run(['sh', 'stest.bash']).returncode
if return_code != 0:
exit(0)
elif re.match('(.+)' + text1 + '(.+)', line):
return_code = subprocess.run(['sh', '1.bash']).returncode
if return_code != 0:
exit(0)
else:
print("something went wrong!Please look into")
还更改您的bash脚本以在失败时返回非零退出代码:
if [something] then
echo "something"
else
echo "exit"
exit 1
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.