如果第一个失败,则阻止在管道中执行python脚本

时间:2019-10-08 11:41:57

标签: python shell

如果第一个脚本失败,是否可以防止脚本在管道中执行?如果这是bash脚本,我们可以设置set -eo pipefail并且脚本不会执行,但是如何在python中完成呢?

will_fail.py

def fail():
    raise Exception

if __name__ == '__main__':
    fail()

print_something.py

def print_something():
    print('something')

if __name__ == '__main__':
    print_something()

执行: python will_fail.py | python print_something.py
输出除外:

Traceback (most recent call last):
  File "will_fail.py", line 5, in <module>
    fail()
  File "will_fail.py", line 2, in fail
    raise Exception
Exception

实际输出:

Traceback (most recent call last):
  File "will_fail.py", line 5, in <module>
**Something**
    fail()
  File "will_fail.py", line 2, in fail
    raise Exception
Exception

通过Something字符串出现在输出的随机行的方式,使我感到困惑。

2 个答案:

答案 0 :(得分:0)

尝试创建一个导入其他两个文件的文件。使其他每个文件返回true或false语句,以显示执行的代码是否没有任何错误。在主文件中,您可以执行以下操作:

if output1 == true:
   runScript2()

答案 1 :(得分:0)

我不知道是否有使用bash脚本的特定原因,但是在这种情况下,我要做的是制作一个脚本并在try / except块中调用这两个函数:

from will_fail import fail
from print_something import print_something

if __name__ == '__main__':
    try:
        fail()
        print_something()
    except:
        # do whatever is needed in case one of the scripts fail

这应该可以按照您描述的方式工作,因此如果print_something失败,将不会执行fail