【发布时间】:2017-07-03 21:00:54
【问题描述】:
我的代码是这样的:
if (not Y):
print ("Can't print")
sys.exit(-1)
我无法理解参数 (-1) 返回的内容是什么?
【问题讨论】:
-
'if (not api): print ("Can't Authenticate") sys.exit(-1)'
标签: sys
我的代码是这样的:
if (not Y):
print ("Can't print")
sys.exit(-1)
我无法理解参数 (-1) 返回的内容是什么?
【问题讨论】:
标签: sys
sys.exit(-1) 告诉程序退出。它基本上只是阻止python代码继续执行。 -1 只是传入的状态码。一般 0 表示执行成功,任何其他数字(通常为 1)表示发生故障。
【讨论】:
调用sys.exit(n) 告诉解释器停止执行并将n 返回给操作系统。这个值是多少取决于操作系统。
例如在 UNIX 上($? 是最后的退出状态):
$ python -c "import sys; sys.exit(-1)"
$ echo $?
255
这是因为它将返回值视为无符号 8 位值(请参阅here)。在 Windows 上,该值将是一个无符号的 32 位值(来自 here),因此是 4294967295。
正如您在第一个链接中看到的,惯例是在成功退出时返回0,否则返回非零值。有时您会看到应用程序对其状态代码有一定的约定。
例如,程序 wget 在其手册页中有一个部分告诉您发生错误的原因:
EXIT STATUS
Wget may return one of several error codes if it encounters problems.
0 No problems occurred.
1 Generic error code.
2 Parse error---for instance, when parsing command-line options, the .wgetrc or .netrc...
3 File I/O error.
4 Network failure.
5 SSL verification failure.
6 Username/password authentication failure.
7 Protocol errors.
8 Server issued an error response.
成功时返回0 的约定对于编写脚本非常有帮助:
$ if python -c "import sys; sys.exit(-1)"; then echo "Everything fine"; else echo "Not good"; fi
Not good
$ if python -c "import sys; sys.exit(0)"; then echo "Everything fine"; else echo "Not good"; fi
Everything fine
【讨论】: