1

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?

PforPython
  • 58
  • 7

1 Answers1

2

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/