[英]How to exit a program: sys.stderr.write() or print
I am writing a small app and I need to quit the program multiple number of times.我正在编写一个小应用程序,我需要多次退出该程序。
Should I use:我应该使用:
sys.stderr.write('Ok quitting')
sys.exit(1)
Or should I just do a:或者我应该做一个:
print 'Error!'
sys.exit(1)
Which is better and why?哪个更好?为什么? Note that I need to do this a lot.
请注意,我需要经常这样做。 The program should completely quit.
该程序应该完全退出。
sys.exit('Error!')
If another type of object is passed, None is equivalent to passing zero, and any other object is printed to sys.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.
如果传递了另一种类型的对象,则 None 相当于传递零,任何其他对象都会打印到 sys.stderr 并导致退出代码为 1。特别是, sys.exit("some error message") 是一个快速发生错误时退出程序的方法。
They're two different ways of showing messages.它们是显示消息的两种不同方式。
print
generally goes to sys.stdout
and you know where sys.stderr
is going. print
通常转到sys.stdout
并且您知道sys.stderr
。 It's worth knowing the difference between stdin, stdout, and stderr .有必要了解stdin、stdout 和 stderr之间的区别。
stdout
should be used for normal program output, whereas stderr
should be reserved only for error messages (abnormal program execution). stdout
应该用于正常的程序输出,而stderr
应该只保留用于错误消息(异常程序执行)。 There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors.有用于拆分这些流的实用程序,它允许您的代码用户区分正常输出和错误。
print
can print on any file-like object, including sys.stderr
: print
可以在任何类似文件的对象上打印,包括sys.stderr
:
print >> sys.stderr, 'My error message'
The advantages of using sys.stderr
for errors instead of sys.stdout are:使用
sys.stderr
代替 sys.stdout 的优点是:
stdout
to a file, they still see errors on the screen.stdout
重定向到文件,他们仍然会在屏幕上看到错误。sys.stderr
is redirected to a log file there is less chance that the program will crash before the error was logged.sys.stderr
重定向到日志文件,则程序在记录错误之前崩溃的可能性较小。 It's worth noting that there's a third way you can provide a closing message:值得注意的是,您可以通过第三种方式提供结束消息:
sys.exit('My error message')
This will send a message to stderr
and exit.这将向
stderr
发送一条消息并退出。
If it's an error message, it should normally go to stderr
- but whether this is necessary depends on your use case.如果这是一条错误消息,它通常应该转到
stderr
- 但是否有必要取决于您的用例。 If you expect users to redirect stdin
, stderr
and stdout
, for example when running your program from a different tool, then you should make sure that status information and error messages are separated cleanly.如果您希望用户重定向
stdin
、 stderr
和stdout
,例如从不同的工具运行您的程序时,那么您应该确保状态信息和错误消息完全分开。
If it's just you using the program, you probably don't need to bother.如果只是您使用该程序,您可能不需要打扰。 In that case, you might as well just raise an exception, and the program will terminate on its own.
在这种情况下,您不妨抛出一个异常,程序将自行终止。
By the way, you can do顺便说一句,你可以做
print >>sys.stderr, "fatal error" # Python 2.x
print("fatal error", file=sys.stderr) # Python 3.x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.