sys.exit('message') 未在空闲状态下打印
sys.exit('message') isn't printing in IDLE
在 python IDLE 中,使用 sys.exit('') 时不会打印指定的错误消息,但在 cmd.exe 中会。为什么?
import sys
try:
print fail
except:
sys.exit("This is an example of an error message")
您的错误消息被打印到 stderr
,它不会在 IDLE 中显示,因为它在子进程中 运行(请参阅此 report of your observation and this related answer)。所以 IDLE 将它写在用于启动 IDLE 的终端上。
文档说明了 sys.exit
的参数:
Some systems have a convention for assigning specific meanings to
specific exit codes, but these are generally underdeveloped; Unix
programs generally use 2 for command line syntax errors and 1 for all
other kind of errors. If another type of object is passed, None is
equivalent to passing zero, and any other object is printed to stderr
and results in an exit code of 1. In particular, sys.exit("some error
message") is a quick way to exit a program when an error occurs.
因此,最安全的方法是仅传递错误代码并使用额外的 print
(或调用自定义退出函数,让用户分析发生的情况)。
在 python IDLE 中,使用 sys.exit('') 时不会打印指定的错误消息,但在 cmd.exe 中会。为什么?
import sys
try:
print fail
except:
sys.exit("This is an example of an error message")
您的错误消息被打印到 stderr
,它不会在 IDLE 中显示,因为它在子进程中 运行(请参阅此 report of your observation and this related answer)。所以 IDLE 将它写在用于启动 IDLE 的终端上。
文档说明了 sys.exit
的参数:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.
因此,最安全的方法是仅传递错误代码并使用额外的 print
(或调用自定义退出函数,让用户分析发生的情况)。