The script I am writing should exit back to the shell prompt with a helpful message if the data to be processed is not exactly right. The user should fix the problems flagged until the script is happy and no longer exits with error messages. I am developing the script with TTD, so I write a pytest
test before I write the function.
The most heavily up-voted answer here suggests that scripts be edited by calling sys.exit
or raising SystemExit
.
The function:
def istext(file_to_test):
try:
open(file_to_test).read(512)
except UnicodeDecodeError:
sys.exit('File {} must be encoded in UTF-8 (Unicode); try converting.'.format(file_to_test))
passes this test (where _non-text.png
is a PNG file, i.e., not encoded in UTF-8):
def test_istext():
with pytest.raises(SystemExit):
istext('_non-text.png')
However, the script continues to run, and statements placed after the try/except
block execute.
I want the script to completely exit every time so that the user can debug the data until it is correct, and the script will do what it is supposed to do (which is to process a directory full of UTF-8 text files, not PNG, JPG, PPTX... files).
Also tried:
The following also passes the test above by raising an exception that is a sub-class of SystemExit
, but it also does not exit the script:
def istext(file_to_test):
class NotUTF8Error(SystemExit): pass
try:
open(file_to_test).read(512)
except UnicodeDecodeError:
raise NotUTF8Error('File {} must be UTF-8.'.format(file_to_test))