在python中运行bash命令并处理错误

2024-10-01 15:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python程序中运行一组bash脚本命令。我必须逐个运行命令,并处理每个命令的错误和异常。为此,我使用subprocess模块和call函数,如下所示:

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

正如预期的那样,这个命令打印“testing”,并将result的值设置为0,这意味着该命令已成功执行。或者,在以下命令的情况下:

^{pr2}$

它打印“/bin/sh:1:echso:notfound”,并将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 

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


Tags: 模块命令程序脚本bash列表错误error
3条回答

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

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

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

你差不多都提到过了。给出了一个更详细的列表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).

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

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

相关问题 更多 >

    热门问题