Python 执行shell命令:system

来源:互联网 发布:娄烨 知乎 编辑:程序博客网 时间:2024/04/30 04:52

一,os.system(cmd)
通过此函数执行Linux命令(或shell脚本),返回值为十进制数(对应一个 16 位的二进制数)。低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码
此函数的返回值与Linux命令返回值之间的转换关系:
函数返回值(十进制)转换为16位二进制数,截取其高八位(有关操作系统的命令错误码共有131个,低八位都是零),然后前八位转成的十进制数就是Linux命令的返回值;示例:

os.system()返回值为0  linux命令返回值也为0.os.system()返回值为 256十六位二进制数示为:0000000100000000,高八位转成十进制为 1 ,对应linux命令返回值 1os.system()返回值为 512十六位二进制数示为:0000001000000000,高八位转成十进制为 2 ,对应linux命令返回值 2os.system()返回值为 32512十六位二进制数示为:0111111100000000,高八位转乘十进制为 127,对应linux命令返回值 127

综上:
os.system(“…py”) 的返回值并不是执行程序的返回结果。而是一个16位的数,它的高位才是返回码。也就是说 os.system() 返回 256 即 0×0100,返回码应该是其高位 0×01 即 1。所以要获取程序运行退出的值(比如 C 的main函数中的 return 0),需要处理一下。

ret = os.system('./a.out')ret >>= 8   # 移位

这样才能获取到正确的返回值。另外还要注意: 函数返回值是无符号整数,所以返回负值的时候,打印出来是很大的正值。比如返回-1,python 会获取到255,-2则254,以此类推。所以最好就判断是否为0就可以了,实在要判断自己写的c程序返回值,建议返回0,1,2,3等值,出错返回 -1。

二,os.popen()
返回值是脚本执行过程中的输出内容;os.popen() 可以返回cdm回显的内容,以文件描述符返回.
这种调用方式是通过管道的方式来实现,函数返回一个file-like的对象,里面的内容是脚本输出的内容;

明显地,像调用”ls”这样的shell命令,应该使用popen的方法来获得内容

t_f = os.popen ("ping 192.168.1.1")print t_f.read() #os.popen()返回file read的对象,对其进行read()操作可以看到执行的结果;

for line in os.popen("dir"):    print line

subprocess.Popen
Popen 非常强大,支持多种参数和模式。

#原型:subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)  ##############Popen类中的方法及属性################Popen.pid#获取子进程的进程IDPopen.returncode #获取进程的返回值。如果进程还没有结束,返回None。Popen.poll() #用于检查子进程是否已经结束。设置并返回returncode属性。Popen.wait() 等待子进程结束。设置并返回returncode属性。Popen.communicate(input=None)#与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。 Communicate() 返回一个元组:(stdoutdata, stderrdata)。注意:如果希望通过进程的 stdin 向其发送数据,在创建 Popen 对象的时候,参数 stdin 必须被设置为 PIPE。同样,如果希望从 stdout 和 stderr 获取数据,必须将 stdout 和stderr 设置为 PIPE。Popen.kill()#杀死子进程;Popen.send_signal(signal) # 向子进程发送信号。Popen.terminate()# 停止(stop)子进程。在windows平台下,该方法将调用Windows API erminateProcess()来结束子进程。Popen.stderr, Popen.stdout, Popen.stdin # 在创建 Popen 对象时,参数 stderr,stdin,stdout 可以被设置为 PIPE ,# 通常通过 args 参数来设定要运行的程序 # executeable 用于指定可执行程序。一般情况下我们通过 args 参数来设置所要运行的程序。如果将参数 shell 设为 True,executable将指定程序使用的shell。在windows平台下,默认的shell由COMSPEC环境变量来指定。# stdin,stdout,stderr 分别表示程序的标准输入、输出、错误句柄。它们可以是PIPE,文件描述符或文件对象,也可以设置为None,表示从父进程继承;# preexec_fn 只在 Unix 平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用。# Close_sfs:在windows平台下,如果 close_fds 被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。我们不能将 close_fds 设置为 True 同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr);# shell 设为 true,程序将通过 shell 来执行。# cwd 用于设置子进程的当前目录# env 是字典类型,用于指定子进程的环境变量。如果 env = None,子进程的环境变量将从父进程中继承。# Universal_newlines:不同操作系统下,文本的换行符是不一样的。如:windows 下用 ’/r/n’ 表示换,而 Linux 下用 ‘/n’。如果将此参数设置为 True,Python 统一把这些换行符当作’/n’来处理# startupinfo 与 createionflags 只在windows下用效,它们将被传递给底层的CreateProcess()函数,用 于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等。subprocess.PIPE# 在创建Popen对象时,subprocess.PIPE 可以初始化 stdin, stdout或stderr 参数,表示与子进程通信的标准流。subprocess.STDOUT# 创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。
from subprocess import Popen, PIPEp = Popen("cp -rf a/* b/", shell=True, stdout=PIPE, stderr=PIPE)  p.wait()  if/while p.returncode != 0:      print "Error."      return -1  
from subprocess import Popen,PIPE p2 = Popen('cd',shell=True,stdout=PIPE,cwd='E:\svnworking')p2.wait()print "当前目录:%s" %p2.stdout.read()# cwd 用来指定新建的子进程的工作目录,当涉及到相对路径的时候可能需要指定cwd# 默认时,创建的子进程与Popen调用所在文件的工作目录相同;
#获取Popen的返回值及输出,用于调用另外一个脚本;from subprocess import Popen,PIPEp = Popen('python ' + path + '\getCurPath.py', stdout=PIPE, stderr=PIPE)p.wait()if(p.returncode == 0):    print "stdout:%s" %p.stdout.read()

commands

(status, output) = commands.getstatusoutput(cmd)print status, output#用os.popen()执行命令cmd,然后返回两个元素的元组(status,result)commands.getoutput(cmd)#只返回执行的结果,忽略返回值;commands.getstatus(cmd)#只返回返回值
#  linux 命令执行后无论成功与否都有一个返回值:#  如果为 0,则表示命令执行成功,其它值则表示错误,具体的错误码含义如下: "OS error code   1:  Operation not permitted" "OS error code   2:  No such file or directory" "OS error code   3:  No such process" "OS error code   4:  Interrupted system call" "OS error code   5:  Input/output error" "OS error code   6:  No such device or address" "OS error code   7:  Argument list too long" "OS error code   8:  Exec format error" "OS error code   9:  Bad file descriptor" "OS error code  10:  No child processes" "OS error code  11:  Resource temporarily unavailable" "OS error code  12:  Cannot allocate memory" "OS error code  13:  Permission denied" "OS error code  14:  Bad address" "OS error code  15:  Block device required" "OS error code  16:  Device or resource busy" "OS error code  17:  File exists" "OS error code  18:  Invalid cross-device link" "OS error code  19:  No such device" "OS error code  20:  Not a directory" "OS error code  21:  Is a directory" "OS error code  22:  Invalid argument" "OS error code  23:  Too many open files in system" "OS error code  24:  Too many open files" "OS error code  25:  Inappropriate ioctl for device" "OS error code  26:  Text file busy" "OS error code  27:  File too large" "OS error code  28:  No space left on device" "OS error code  29:  Illegal seek" "OS error code  30:  Read-only file system" "OS error code  31:  Too many links" "OS error code  32:  Broken pipe" "OS error code  33:  Numerical argument out of domain" "OS error code  34:  Numerical result out of range" "OS error code  35:  Resource deadlock avoided" "OS error code  36:  File name too long" "OS error code  37:  No locks available" "OS error code  38:  Function not implemented" "OS error code  39:  Directory not empty" "OS error code  40:  Too many levels of symbolic links" "OS error code  42:  No message of desired type" "OS error code  43:  Identifier removed" "OS error code  44:  Channel number out of range" "OS error code  45:  Level 2 not synchronized" "OS error code  46:  Level 3 halted" "OS error code  47:  Level 3 reset" "OS error code  48:  Link number out of range" "OS error code  49:  Protocol driver not attached" "OS error code  50:  No CSI structure available" "OS error code  51:  Level 2 halted" "OS error code  52:  Invalid exchange" "OS error code  53:  Invalid request descriptor" "OS error code  54:  Exchange full" "OS error code  55:  No anode" "OS error code  56:  Invalid request code" "OS error code  57:  Invalid slot" "OS error code  59:  Bad font file format" "OS error code  60:  Device not a stream" "OS error code  61:  No data available" "OS error code  62:  Timer expired" "OS error code  63:  Out of streams resources" "OS error code  64:  Machine is not on the network" "OS error code  65:  Package not installed" "OS error code  66:  Object is remote" "OS error code  67:  Link has been severed" "OS error code  68:  Advertise error" "OS error code  69:  Srmount error" "OS error code  70:  Communication error on send" "OS error code  71:  Protocol error" "OS error code  72:  Multihop attempted" "OS error code  73:  RFS specific error" "OS error code  74:  Bad message" "OS error code  75:  Value too large for defined data type" "OS error code  76:  Name not unique on network" "OS error code  77:  File descriptor in bad state" "OS error code  78:  Remote address changed" "OS error code  79:  Can not access a needed shared library" "OS error code  80:  Accessing a corrupted shared library" "OS error code  81:  .lib section in a.out corrupted" "OS error code  82:  Attempting to link in too many shared libraries" "OS error code  83:  Cannot exec a shared library directly" "OS error code  84:  Invalid or incomplete multibyte or wide character" "OS error code  85:  Interrupted system call should be restarted" "OS error code  86:  Streams pipe error" "OS error code  87:  Too many users" "OS error code  88:  Socket operation on non-socket" "OS error code  89:  Destination address required" "OS error code  90:  Message too long" "OS error code  91:  Protocol wrong type for socket" "OS error code  92:  Protocol not available" "OS error code  93:  Protocol not supported" "OS error code  94:  Socket type not supported" "OS error code  95:  Operation not supported" "OS error code  96:  Protocol family not supported" "OS error code  97:  Address family not supported by protocol" "OS error code  98:  Address already in use" "OS error code  99:  Cannot assign requested address" "OS error code 100:  Network is down" "OS error code 101:  Network is unreachable" "OS error code 102:  Network dropped connection on reset" "OS error code 103:  Software caused connection abort" "OS error code 104:  Connection reset by peer" "OS error code 105:  No buffer space available" "OS error code 106:  Transport endpoint is already connected" "OS error code 107:  Transport endpoint is not connected" "OS error code 108:  Cannot send after transport endpoint shutdown" "OS error code 109:  Too many references: cannot splice" "OS error code 110:  Connection timed out" "OS error code 111:  Connection refused" "OS error code 112:  Host is down" "OS error code 113:  No route to host" "OS error code 114:  Operation already in progress" "OS error code 115:  Operation now in progress" "OS error code 116:  Stale NFS file handle" "OS error code 117:  Structure needs cleaning" "OS error code 118:  Not a XENIX named type file" "OS error code 119:  No XENIX semaphores available" "OS error code 120:  Is a named type file" "OS error code 121:  Remote I/O error" "OS error code 122:  Disk quota exceeded" "OS error code 123:  No medium found" "OS error code 124:  Wrong medium type" "OS error code 125:  Operation canceled" "OS error code 126:  Required key not available" "OS error code 127:  Key has expired" "OS error code 128:  Key has been revoked" "OS error code 129:  Key was rejected by service" "OS error code 130:  Owner died" "OS error code 131:  State not recoverable"
0 0