os.system('cmd')在linux和windows系统下返回值的差异


今天,用os.system('cmd')分别在windows和linux平台上执行同一ping命令,命令执行失败时返回码不同,windows为1,而linux下返回为256,如下:

linux下:

>>> import os,sys
>>> os.system('ping -c 1 192.168.1.1 > /dev/null')
0
>>> os.system('ping -c 1 192.168.1.2 > /dev/null')
256
>>>

windows下:

>>> import os,sys
>>> os.system('ping -n 1 -w 200 192.168.1.1 > nul')
0
>>> os.system('ping -n 1 -w 200 192.168.1.2 > nul')
1
>>>

查看system函数的python在线手册如下:

os.system(command)

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream.

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

简单总结一下:

os.system('cmd')的功能是在子shell中将cmd字符串作为作为命令执行,cmd命令执行后产生的任何输出将被发送到命令解释器的标准输出流。同时状态返回码也将输出到解释器标准输出流。但值得注意的是:返回状态码在windows和linux下的意义不同,对于windows,返回值就是命令执行后的退出状态码,而linux平台上,从上面的手册描述来看,退出状态码是经过了编码的,编码构成如下:

exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

也就是说,linux平台上返回值(10进制)需转换为16位二进制数,也就是2个字节,高字节代表退出码。因此,将高字节对应的十进制数才是命令执行后的退出码。

就拿前面的退出码256来说:

os.system(‘cmd’)返回值为0                      linux命令返回值也为0.

os.system(‘cmd')返回值为256,对应二进制数为:00000001,00000000,高八位对应十进制为1,因此 linux命令返回值 1

其余以此类推

如果脚本中一定要准确判断返回值,只需对linux平台下的返回值进行截取高8位就可以了。