如何绕过python中sys.exit()的0-255范围限制?
在 python 中(在 Linux 系统上),我使用 os.system() 启动命令并检索返回码。如果该返回代码不同于 0,我想让程序以相同的返回代码退出。所以我写道:
ret = os.system(cmd)
if ret != 0:
print "exit with status %s" % ret
sys.exit(ret)
当返回代码低于256时,它工作正常,但是当它大于255时,使用的退出代码是0。如何使sys.exit()接受大于255的代码?
编辑:限制实际上是 255
事实上,ret
变量接收 256,但 sys.exit()
无法使用它,因此程序返回 0。当我手动启动 cmd
时,我看到它返回 1,而不是 256。
In python (on a Linux system), I'm launching a command using os.system()
and retrieving the return code. If that return code is different from 0, I would like to make the program exit with that same return code. So I wrote:
ret = os.system(cmd)
if ret != 0:
print "exit with status %s" % ret
sys.exit(ret)
When the return code is lower than 256, it works fine, but when it's greater than 255, the exit code used is 0. How can I make sys.exit() accept codes greater than 255?
Edit: the limit is actually 255
In fact, the ret
variable receives 256, but sys.exit()
fails to use it, so the program returns 0 instead. When I launch cmd
manually, I see that it returns 1, not 256.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,文档表明
所以我需要处理 sys.exit() 返回的数字,以便检索真正的退出状态,如下所示:
现在它可以工作了: ret 包含 1 而不是 256。
Actually, the documentation indicates that
So I need to process the number returned by sys.exit() in order to retrieve the real exit status, like so:
And now it works: ret contains 1 instead of 256.
你
不能不应该,因为系统为自己保留了128以上的退出代码。如果返回码是从0到127,则表示程序自行退出。如果返回码高于128,则意味着程序被系统信号(例如SIGKILL或SIGTERM)终止。信号编号是结果代码减 128。我认为您需要检测它并进行其他类型的输出指示。也许将返回代码打印到 STDOUT,然后返回 0(正常退出,正常输出)或 1(cmd 有一个非零返回值,输出意味着什么)。
编辑:显然(来自 此评论),Python 比 shell 脚本更聪明...要将其放回常规 Linux 退出代码,请尝试以下操作:
尽管这会忽略核心转储信息。
You
can'tshouldn't, because the system reserves exit codes above 128 for itself. If the return code is from 0 to 127, it means that the program exited by itself. If the return code is higher than 128, it means that the program was terminated by a system signal (e.g. SIGKILL or SIGTERM). The signal number is the result code minus 128.You'll need to detect it and make some other kind of output indication, I think. Perhaps print the return code to STDOUT and then return with either 0 (normal exit, normal output) or 1 (cmd had a non-zero return value, output means something).
edit: Apparently (from this comment), Python is more clever than a shell script... To put it back into a regular Linux exit code, try this:
Although this ignores the core-dump information.
对我有用(CentOS 5.5,Python 2.6.5):
Works for me (CentOS 5.5, Python 2.6.5):