Predictive Hacks

How to Terminate a Python Script

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.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.