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
CodePudding user response:
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.