GitHub Actions上のPythonでexit(1)する時、printの標準出力は表示されない

2023/03/19に公開

TL;DR

GitHub Actions 上で Python を実行して、入力値のバリデーションが引っかかった場合sys.exit(1)と、その理由を出力しようとした。

エラーが発生した場合は標準エラー出力に出力されるため、print関数にfile=sys.stderrを指定してあげる必要がある。

print(f'Error: {message}', file=sys.stderr)

詳細

以下のようなPythonコードをGitHub Actions上で実行していた。このコードは、入力されたmakefileが存在しない場合、sys.exit(1)を呼び出してエラー終了するようになっている。

def validate_inputs(makefile: str) -> bool:
    ok: bool = True
    if not os.path.exists(makefile):
        print(f'Error: {makefile} is not found')
        ok &= False
    return ok

def main(makefile: str):
    if not validate_inputs(makefile):
        sys.exit(1)
    ....

しかし、エラーが発生した場合、Error: {makefile} is not foundが出力されなかった。

原因は、出力先が標準出力になっていたためだった。以下のように、出力先を標準エラー出力に書き換えることで、期待するようにエラーメッセージを出力することができる。

def validate_inputs(makefile: str) -> bool:
    ok: bool = True
    if not os.path.exists(makefile):
        print(f'Error: {makefile} is not found', file=sys.stderr)
        ok &= False
    return ok

標準エラー出力に出力することで、GitHub Actions上でエラーが発生した場合に、エラーメッセージが表示されるようになる。

Discussion