2014-12-05 67 views
3

我试图在python程序中运行一组bash脚本命令。我必须逐个运行命令并处理每个命令的错误和异常。为此,我使用与call功能波纹管的subprocess模块:在python中运行bash命令并处理错误

result = subprocess.call("echo testing", shell = True) 

预期这个命令打印“测试”和设置的result的值设置为0,这意味着已成功执行的命令。或者,在以下命令的情况:

result = subprocess.call("echso testing", shell = True) 

它打印“/ bin/sh的:1:echso:未发现”,并设置的result到127的数值,这意味着命令echso是无效的。 我的问题是,我可以在哪里找到这些错误编号的完整列表,以及可以用于错误处理的描述?到目前为止,我发现一个退出错误列表如下:

1: general errors 
2: misuse of shell builtins (pretty rare) 
126: cannot invoke requested command 
127: command not found error 
128: invalid argument to “exit” 
128+n: fatal error signal “n” (for example, kill -9 = 137) 
130: script terminated by Ctrl-C 

这是全部,还是你知道更多的错误代码与描述?

+1

该列表中你是因为它得到一样好。每个程序都可以自由使用它想要的任何退出代码。除了“非零等于错误”之外,你实在无法依赖任何东西。也就是说,你可以捕获'stderr'并提供给用户。 – kindall 2014-12-05 14:42:54

+1

可能的重复http://stackoverflow.com/questions/1101957/are-there-any-standard-exit-status-codes-in-linux – runDOSrun 2014-12-05 14:45:36

回答

0

bash手册页有一个部分3.7.5 Exit Status,其中涵盖了您指定的值(尽管我没有在其中看到130)。

除此之外,我不知道有什么好的标准。

sysexits.h但我不确定有多少人实际使用它(也可在Linux上使用)。

+0

这就是为什么我更喜欢另一种解决方案。它至少可以处理所有的情况 – vks 2014-12-05 14:51:39

+0

@vks不,它不处理所有的情况。处理不写入stderr但返回失败返回码的内容。 – 2014-12-05 15:02:16

-1
result = subprocess.Popen("echo testing", shell = True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
output,err=result.communicate() 
if output: 
    print "success" 
else: 
    print err 

而不是找到错误的数字,你可以直接找到错误,并处理它们。

+1

这不是问题的答案。 – 2014-12-05 14:40:03

+0

这是如何回答他可以在哪里找到shell的退出编码器列表的问题? – RedX 2014-12-05 14:40:17

+0

这给你从运行命令标准错误(我相信)并不总是相同的事情。 – 2014-12-05 14:43:02

0

你几乎提到了所有这些。一个更详尽的列表给出here,这里是关于他们每个人的一些有用的信息:

reserved exit codes

According to the above table, exit codes 1 - 2, 126 - 165, and 255 have special meanings, and should therefore be avoided for user-specified exit parameters. Ending a script with exit 127 would certainly cause confusion when troubleshooting (is the error code a "command not found" or a user-defined one?). However, many scripts use an exit 1 as a general bailout-upon-error. Since exit code 1 signifies so many possible errors, it is not particularly useful in debugging.

There has been an attempt to systematize exit status numbers (see /usr/include/sysexits.h), but this is intended for C and C++ programmers. A similar standard for scripting might be appropriate. The author of this document proposes restricting user-defined exit codes to the range 64 - 113 (in addition to 0, for success), to conform with the C/C++ standard. This would allot 50 valid codes, and make troubleshooting scripts more straightforward.

Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225).