今天,用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位就可以了。