How to fail a gitlab CI pipeline if the python script throws error code 1?

Question:

I have a python file that opens and checks for a word. The program returns 0 if pass and 1 if fails.

import sys

word = "test"

def check():
    with open("tex.txt", "r") as file:
        for line_number, line in enumerate(file, start=1):  
            if word in line:
                return 0
            
        return 1

is_word_found = check() # store the return value of check() in variable `is_word_found`
print(is_word_found)
output

1

I have gitlab-ci.yml that runs this python script in a pipeline.

image: davidlor/python-git-app:latest

stages:
    - Test
Test_stage:
   tags:
        - docker
   stage: Test
   script:
        - echo "test stage started"
        - python verify.py

When this pipeline runs the python code prints 1 that means the program failed to find the test word. But the pipeline passes successfully.

I want to fail the pipeline if the python prints 1. Can somebody help me here?

Asked By: PforPython

||

Answers:

You can use sys.exit(is_word_found). But remember you use sys module (import sys).

Like this:

import sys
word = "test"
def check():
    with open("tex.txt", "r") as file:
        for line_number, line in enumerate(file, start=1):  
            if word in line:
                return 0
        return 1
is_word_found = check() 
sys.exit(is_word_found)

However, you have a lot of other options too. check out this:
https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.