Python 提升系统出口关闭标准输入
在编写控制台时,我想实现一个查询,询问用户是否真的想退出。我试图捕获SystemExit,同时引发SystemExit(exit的作用,在我的项目中的多个函数中使用)关闭stdin。如何在不关闭stdin的情况下捕获系统出口?以下是console程序的基本结构:Python 提升系统出口关闭标准输入,python,input,Python,Input,在编写控制台时,我想实现一个查询,询问用户是否真的想退出。我试图捕获SystemExit,同时引发SystemExit(exit的作用,在我的项目中的多个函数中使用)关闭stdin。如何在不关闭stdin的情况下捕获系统出口?以下是console程序的基本结构: isDirty = False # structure holding the commands @vars class commands: exit = exit def help(): print
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)
控制台输入/输出:
$ 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.
$python sysexiter.py
]帮助
退出交互式控制台
帮助显示此帮助消息
dirty设置dirtyflag,在退出时询问
]肮脏的
]出口
肮脏!还是退出?回溯(最近一次呼叫最后一次):
文件“sysexiter.py”,第20行,在
命令[ln]()
文件“/usr/lib/python3.6/\u sitebuiltins.py”,第26行,在调用中__
升起系统出口(代码)
系统退出:无
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“sysexiter.py”,第23行,在
如果输入(“脏!是否仍要退出?”)[0],“JY”中的upper():
ValueError:对关闭的文件执行I/O操作。
exit()
关闭stdin,引发异常~这是python解释器的错误还是它为什么关闭stdin?这是一种支持特定shell()的解决方法。现在,如果您需要使用stdin,最好自己提出异常。