如果在获取和退出子流程时出错,则退出python脚本

时间:2019-01-22 06:53:22

标签: python shell

我目前正在使用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脚本无法正确退出。有人可以指出要修改哪些内容以解决问题吗?

1 个答案:

答案 0 :(得分:0)

如果可以使用异常退出,请更改代码以使用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
相关问题