If you have built a Python script and would like to terminate it once it meets a condition, then you can work with the sys
module and the exit()
method. Let’s consider the following python script, my_simple.py
, that writes a txt file.
# the 'w' mode is for write with open('newfile.txt', mode='w') as my_file: for n in range(10): # add text my_file.write(f'This is a line number {n}\n')
If we run the script in the terminal like:
python my_simple.py
We will get the newfile.txt
with the following content.
This is a line number 0
This is a line number 1
This is a line number 2
This is a line number 3
This is a line number 4
This is a line number 5
This is a line number 6
This is a line number 7
This is a line number 8
This is a line number 9
Assume now, that we would like to terminate the script when the n in the for loop is greater than 4 and it is an even number. We can achieve that by adding an if statement and the sys.exit()
command that terminates the script. The my_simple.py
becomes:
import sys # the 'w' mode is for write with open('newfile.txt', mode='w') as my_file: for n in range(10): # add text to the new file my_file.write(f'This is a line number {n}\n') if n%2 == 0 and n>4: sys.exit()
And by running it in the command line:
python my_simple.py
We get the newfile.txt
with the following content.
This is a line number 0
This is a line number 1
This is a line number 2
This is a line number 3
This is a line number 4
This is a line number 5
This is a line number 6
As you can see, the script was terminated once it met the condition.