-
-
Notifications
You must be signed in to change notification settings - Fork 33.7k
Description
Bug report
Bug description:
Hello!
Sorry if this has been reported before, but I didn't find something similar by looking through the issues here.
Consider this code snippet run in any kind of interactive console, e.g. the REPL or VS Code's new Native REPL:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--test-arg")
parser.parse_args(["--test-arg"]) # No argument for --test-arg so as to raise the errorBecause the default for ArgumentParser is exit_on_error=True, this will cause the interactive environment to exit. It is especially bad in VS Code because the cell simply hangs with the timer continuing the count, it is unable to terminate and upon closing/reopening the REPL the reported error is the very (not) helpful "Connection is closed".
Python's REPL also behaves similarly, exiting immediately with code 2. I think that the interactive console should continue running when an incorrect argument is passed in the evaluated code, or indeed if exit is not explicitly called by the user. Granted, the (to me, more) obvious behavior can be achieved by passing exit_on_error=False to ArgumentParser but this creates a potential for mistakes when moving between normal code and the REPL for, say, some debugging/testing.
I don't know what the sensible approach should be, however. When in a program this print-error-and-exit default is sensible, but when in interactive print-error-and-return is the expected behavior. Maybe take a step back and don't actually exit the REPL when exit is not explicitly called from the user, but only go back to the Read phase?
Apologies for the long message...
CPython versions tested on:
3.12, 3.14
Operating systems tested on:
Linux