Understanding Interpreter Exit Exceptions
00:00
At some point or another, all programs come to an end. Python also provides built-in exceptions for situations where this needs to happen. In this lesson, you look at SystemExit
.
00:10 This can be important for indicating an appropriate exit status to the user when the program ends. Especially useful in command line apps, as you’ll soon see.
00:18
And KeyboardInterrupt
in interactive Python sessions, this is used to terminate code execution typically by hitting the key combination Ctrl+C.
00:28 In general, these are exceptions that you want to end your program and shouldn’t be caught as that could prevent the application from terminating altogether, which would not be a good thing.
00:37 And there’s one more warning on this lesson. When a program is suddenly terminated using one of these, you might be leaving the system with untied loose ends, leftover temp files, open network connections, that kind of thing.
00:51
For more fine-tuned control over exit behavior, you can use the atexit
module from the standard library. But we’re here to see exceptions, and see them we shall. Meet me in your IDE of choice.
01:05
So I’m here in Visual Studio Code where you’ll be writing a command-line app that reads out the contents of a directory emulating the Unix command-line program ls
. First imports. import sys
and from pathlib import Path
.
01:22
This app will take exactly one argument, the directory, whose contents you want to view. You’ll start by checking the length of the .argv
attribute of the sys
module to check if the correct number of arguments have been provided.
01:34
If not, raise SystemExit
with the exit code two. args_count = len(sys.argv)
01:42
If args_count
is greater than two,
01:46
print the f-string "One argument expected,
01:51
got
, the value of args_count - 1"
.
01:56
And raise SystemExit
passing in the integer 2
. elif args_count
is less than two, print, "You must specify the target directory"
02:10
And raise SystemExit
also passing in the integer two. Exit code two is used here to indicate an invalid syntax, specifically the wrong number of arguments.
02:22
sys.argv
always holds at least one argument, the Python filename. So the second argument should be the target directory. That’s why we expect there to be a total of two arguments.
02:32
And after confirming the argument count, you can grab the single argument and create a Path
object out of it. target_dir = Path(sys.argv
[1])
.
02:46
Now because you expect the resulting Path
object to represent a directory, you can use the .is_dir()
method to confirm it. If the path doesn’t lead to a valid directory, raise another SystemExit
with the exit code one, indicating a general error in the program’s execution.
03:02
If not target_dir.is_dir()
03:07
print "The target directory doesn't exist"
03:17
Finally, if the path does lead to a valid directory, you’re good to go. Iterate over its contents using the .iterdir()
method and print the entries. for entry in target_dir.iterdir()
03:34
Now you’re ready to save the file and open up the integrated terminal and give it a try. python ls.py
You must specify the target directory
.
03:45
It looks like it failed because args_count
was less than two, which sounds right. So how can you check the exit code? It’s actually stored in the shell in a special variable called ?
.
03:56
And you can do that using the echo
command. echo $?
- Two, exit code two, perfect. Now try running the app with too many arguments.
04:07
python ls.py /home /etc
One argument expected, got two. This also looks right. Confirm the exit code as before `echo $?’ - Two. And to check the next failure mode, try passing in a directory that doesn’t exist.
04:28
python ls.py non_existent
The target directory doesn’t exist. That looks right, and if we check the exit code again, `echo $?’ - Exit code one.
04:42
Perfect. All that’s left to do is see if the ls
program actually works. Use python ls.py .
to read the contents of the current directory.
04:54
Looks good to me. The two files I can see in Visual Studio Code Explorer and that weird .DS_Store
file that macOS seems to put in every folder.
05:03
Since the program succeeded, you should see an exit code of zero. echo $?
one more time, and zero it is. And real quick, while we’re here to try out a KeyboardInterrupt
, open the REPL. python
and write an infinite loop: while True: print(
"Hello")
. This will run forever, continually printing “Hello”, until Ctrl+C, you hit the KeyboardInterrupt
key combination. Again, this is super useful for when a program is hanging or just taking a really long time.
05:42 For some reason, you definitely wouldn’t want to catch this exception because then terminating the program would be a lot more annoying. Alright. We have one more exception to discuss and it’s a doozy.
Become a Member to join the conversation.