Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python program to return exit code 0 if passes and 1 if fails

I have a text file that includes a word like "test". Now what i am trying to do is using python i am opening that text file and search for that word. If the word exists then the python program should return exit code 0 or else 1.

This is the code that i have written that returns 0 or 1.

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
            else:
                return 1

print(check())
output

0

what I want is I want to store this exit code in some variable so that i can pass this to a yaml file. Can someone guide me here how can i store this exit code in a variable? thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you are looking for sys.exit(), but since you edited your question, I am not sure anymore. Try 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() # store the return value of check() in variable `is_word_found`
print(is_word_found) # prints value of `is_word_found` to standard output
sys.exit(is_word_found) # exit the program with status code `is_word_found`

BTW: as @gimix and @VPfB mentioned, your check() function did return a value immediately after it checked the first line of your file. I included a fix for that, now 1 is returned only if the word is not found is any line of your file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading