raising SystemExit closes stdin

时间:2017-06-19 13:57:40

标签: python input

When I am writing a console, I want to implement a query to ask the user if he really wants to quit. I tried to catch SystemExit, while raising SystemExit (what exit does, which is used in multiple functions in my project) closes stdin. How to catch the SystemExit without closeing stdin? Here is the basic structure of the console-program:

isDirty = False

# structure holding the commands
@vars
class commands:
    exit = exit

    def help():
        print(
            "exit     exit the interactive console\n"
            "help     show this help-message\n"
            "dirty    set the dirtyflag, asks on quit"
        )

    def dirty():
        global isDirty
        isDirty = True

while True:
    ln = input(" ]")
    try:
        commands[ln]()
    except SystemExit:
        if isDirty:
            if input("dirty! exit anyway? ")[0].upper() in "JY":
                raise
        else:
            raise
    except BaseException as e:
        # use of another exception. Eg. unknown command
        print(e)

Console in/output:

$ python sysexiterr.py
 ]help
exit     exit the interactive console
help     show this help-message
dirty    set the dirtyflag, asks on quit
 ]dirty
 ]exit
dirty! exit anyway? Traceback (most recent call last):
  File "sysexiterr.py", line 20, in <module>
    commands[ln]()
  File "/usr/lib/python3.6/_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "sysexiterr.py", line 23, in <module>
    if input("dirty! exit anyway? ")[0].upper() in "JY":
ValueError: I/O operation on closed file.

0 个答案:

没有答案