使用python的subprocess模块调用linux系统命令

subprocess模块主要有call()、check_call()、check_output()、Popen()函数,简要描述以下:shell

Main API ======== call(...): Runs a command, waits for it to complete, then returns the return code. check_call(...): Same as call() but raises CalledProcessError() if return code is not 0 check_output(...): Same as check_call() but returns the contents of stdout instead of a return code Popen(...): A class for flexibly executing a command in a new processwindows

Constants
---------
PIPE:    Special value that indicates a pipe should be created
STDOUT:  Special value that indicates that stderr should go to stdout

下面开始介绍subprocess函数的使用方法。缓存

(1)subprocess.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)flex

参数说明:操作系统

args: 要调用的外部系统命令。 bufsize: 默认值为0, 表示不缓存,。为1表示行缓存,。其余正数表示缓存使用的大小,,负数-1表示使用系统默认的缓存大小。 stdin、stdout、stdout 分别表示标准输入、标准输出和标准错误。其值能够为PIPE、文件描述符和None等。默认值为None,表示从父进程继承。 shell Linux:参数值为False时,Linux上经过调用os.execvp执行对应的程序。为Trule时,Linux上直接调用系统shell来执行程序。 Windows:shell参数表示是否使用bat做为执行环境。只有执行windows的dir、copy等命令时才须要设置为True。其余程序没有区别。 executable 用于指定可执行程序。通常状况下咱们经过args参数来设置所要运行的程序。若是将参数shell设为 True,executable将指定程序使用的shell。在windows平台下,默认的shell由COMSPEC环境变量来指定。 preexec_fn 只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行以前被调用 cwd 设置子进程当前目录 env env是字典类型,用于指定子进程的环境变量。默认值为None,表示子进程的环境变量将从父进程中继承。 Universal_newlines 不一样操做系统下,文本的换行符是不同的。如:windows下用’/r/n’表示换,而Linux下用 ‘/n’。若是将此参数设置为True,Python统一把这些换行符看成’/n’来处理。code

Popen对象对应的属性和方法以下:对象

属性: stdin, stdout, stderr, pid, returncode 方法: communicate(self, input=None) -> returns a tuple (stdout, stderr). wait(self) -> Wait for child process to terminate. Returns returncode attribute.继承

经常使用实例进程

一、打印D:\temp目录下建立test目录。直接调用进程,不考虑获取调用命令输出内容和结果码

import subprocess

p = subprocess.Popen(args='mkdir test', shell=True, cwd='d:/temp') p.wait()

二、调用ping命令执行,获取命令执行输出内容

import subprocess

p = subprocess.Popen(args='ping -n 2 -w 3 192.168.1.104', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() print p.stdout.read()

说明:p.stdout、p.stdin、p.stderr为文件对象,可使用文件对象函数,如read()。

(2)subprocess.call()

函数原型:call(*popenargs, **kwargs)。call()调用外部系统命令执行,并返回程序执行结果码。

import subprocess

retcode = subprocess.call('ping -n 2 -w 3 192.168.1.104', shell=True) print retcode

(3)subprocess.check_call()

使用方法同call()。若是调用命令执行成功,返回结果码0,若是执行失败,抛出CalledProcessError.异常。举例以下:

p = subprocess.check_call('ping -n 2 -w 3 192.168.1.105', shell=True)

正在 Ping 192.168.1.105 具备 32 字节的数据: 请求超时。 请求超时。

192.168.1.105 的 Ping 统计信息: 数据包: 已发送 = 2,已接收 = 0,丢失 = 2 (100% 丢失), Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\Python27\lib\subprocess.py", line 186, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'ping -n 2 -w 3 192.168.1.105' returned non-zero exit status 1

(4)subprocess.check_output()

函数原型:check_output(*popenargs, **kwargs)。用法与call()相同。区别是若是执行成功返回的是标准输出内容。若是失败,抛CalledProcessError.异常。

import subprocess

output = subprocess.check_output('ping -n 2 -w 3 192.168.1.104', shell=True) print output

相关文章
相关标签/搜索