Often you’ll see this in open() calls, where failing to properly release the file could cause problems with reading or writing to the file later. Generally, Python releases all the resources you’ve called in your program automatically when it exits, but for certain processes, it’s good practice to encase some limited resources in a with block. Notice the user would never know an EOFError occurred, this can be used to pass default values in the event of poor input or arguments. #print("EOFError: You didn't enter anything!") We can add a finally statement that lets us execute code after we do our error handling in catch $ nano input.py If we don’t want to import extra modules, we can do what exit(), quit() and sys.exit() are doing behind the scenes and raise SystemExit $ python3 Notice that we need to explicitly import a module to call exit(), this might seem like its not an improvement, but it guarantees that the necessary module is loaded because it’s not a good assumption site will be loaded at runtime. For our programs, we should use something like sys.exit $ python3 Neither quit() nor exit() are considered good practice, as they both require the site module, which is meant to be used for interactive interpreters and not in programs. Type "help", "copyright", "credits" or "license" for more information.Įxit() has the same functionality as it is an alias for quit() $ python3 When Python reaches the EOF condition at the same time that it has executed all the code without throwing any exceptions, which is one way Python may exit “gracefully.” The EOFError exception tells us that the Python interpreter hit the end of file (EOF) condition before it finished executing the code, as the user entered no input data. Now, press CTRL X to save and exit the nano window and in your shell type: $ python3 input.pyĪnd press CTRL D to terminate the program while it’s waiting for user input Traceback (most recent call last): Then paste the following into the shell by right-clicking on the PowerShell window name=input("Don't type anything!\n") To demonstrate, let’s try to get user input and interrupt the interpreter in the middle of execution!įirst, from your bash terminal in your PowerShell open a new file called “input.py”: $ nano input.py When the Python interpreter reaches the end of the file (EOF), it notices that it can’t read any more data from the source, whether that be the user’s input through an IDE or reading from a file. The way Python executes a code block makes it execute each line in order, checking dependencies to import, reading definitions and classes to store in memory, and executing pieces of code in order allowing for loops and calls back to the defined definitions and classes. Why does Python automatically exit a script when it’s done? Why does Python automatically exit a script when it’s done?.
0 Comments
Leave a Reply. |