簡體   English   中英

如果第一個失敗,防止 python 腳本在管道中執行

[英]Prevent python script executing in pipeline if first one fails

如果第一個失敗,有沒有辦法防止腳本在管道中執行? 如果這是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 python will_fail.py | python print_something.py
除外 output:

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

實際 output:

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

順便說一句,output 的隨機行出現了Something字符串,讓我感到困惑。

嘗試創建一個導入其他兩個文件的文件。 使其他每個文件都返回 true 或 false 語句,以顯示代碼執行是否沒有任何錯誤。 在主文件中,您可以這樣做:

if output1 == true:
   runScript2()

我不知道使用 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的情況下執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM