我想知道 python 中的 sys.exit(-1) returns 到底是什么?
I want to know what exactly sys.exit(-1) returns in python?
我的代码是这样的:
if (not Y):
print ("Can't print")
sys.exit(-1)
我无法理解论点 (-1
) returns?
sys.exit(-1)
告诉程序退出。它基本上只是阻止 python 代码继续执行。 -1只是传入的状态码。一般0表示执行成功,其他数字(通常为1)表示有问题。
调用sys.exit(n)
告诉解释器停止执行,returnn
到OS。此值取决于操作系统。
例如在 UNIX 上($?
是最后的退出状态):
$ python -c "import sys; sys.exit(-1)"
$ echo $?
255
这是因为它将 return 值视为一个无符号的 8 位值(参见 here). On Windows the value would be an unsigned 32bit value (from here),因此是 4294967295
。
正如您在第一个 link 中所见,约定是 return 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.
成功时returning 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
我的代码是这样的:
if (not Y):
print ("Can't print")
sys.exit(-1)
我无法理解论点 (-1
) returns?
sys.exit(-1)
告诉程序退出。它基本上只是阻止 python 代码继续执行。 -1只是传入的状态码。一般0表示执行成功,其他数字(通常为1)表示有问题。
调用sys.exit(n)
告诉解释器停止执行,returnn
到OS。此值取决于操作系统。
例如在 UNIX 上($?
是最后的退出状态):
$ python -c "import sys; sys.exit(-1)"
$ echo $?
255
这是因为它将 return 值视为一个无符号的 8 位值(参见 here). On Windows the value would be an unsigned 32bit value (from here),因此是 4294967295
。
正如您在第一个 link 中所见,约定是 return 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.
成功时returning 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