使用python的subprocess模块调用linux系统命令
subprocess模块主要有call()、check_call()、check_output()、Popen()函数,简要描述如下:
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 process
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)
参数说明:
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’来处理。
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.
常用实例
1、打印D:\temp目录下创建test目录。直接调用进程,不考虑获取调用命令输出内容和结果码
import subprocess
p = subprocess.Popen(args='mkdir test', shell=True, cwd='d:/temp')
p.wait()
2、调用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 "", line 1, in
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
使用python的subprocess模块调用linux系统命令的更多相关文章
- Python中subprocess 模块 创建并运行一个进程
python的subprocess模块,看到官方声明里说要尽力避免使用shell=True这个参数,于是测试了一下: from subprocess import call import shlex ...
- (转载)Python 的 JPype 模块调用 Jar 包
Python 的 JPype 模块调用 Jar 包 背景与需求 最近学习并安装使用了HttpRunner框架去尝试做接口测试,并有后续在公司推广的打算. HttpRunner由Python开发,调用接 ...
- python的subprocess模块(写的不错留作查询)
python的subprocess模块 subprocess模块是python从2.4版本开始引入的模块.主要用来取代 一些旧的模块方法,如os.system.os.spawn*.os.popen*. ...
- python 利用python的subprocess模块执行外部命令,获取返回值
有时执行dos命令需要保存返回值 需要导入库subprocess import subprocess p = subprocess.Popen('ping www.baidu.com', shell= ...
- python基础--subprocess模块
可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen* --废弃 popen2.* --废弃 commands.* ...
- Python的subprocess模块(一)
原文连接:http://www.cnblogs.com/wang-yc/p/5624880.html 一.简介 subprocess最早在2.4版本引入.用来生成子进程,并可以通过管道连接他们的输入/ ...
- Python之subprocess模块、sys模块
一.subprocess模块 # import os # os.system('tasklist') #类似cmd输入系统命令 ''' subprocess的目的就是启动一个新的进程并且与之通信. s ...
- Python的subprocess模块(二)
原文:http://blog.chinaunix.net/uid-26000296-id-4461522.html 一.subprocess 模块简介 subprocess最早是在2.4版本中引入的. ...
- Python,subprocess模块(补充)
1.subprocess模块,前戏 res = os.system('dir') 打印到屏幕,res为0或非0 os.popen('dir') 返回一个内存对象,相当于文件流 a = os.popen ...
随机推荐
- 使用VSCODE开发UE4
完全可行,速度很快,智能提示.代码格式化.查找Symbol等等都不比VS+Visual AssistX 差. 准备 打开编辑器的Editor Preferences>Source Code,选择 ...
- mysql报错处理:incompatible with sql_mode=only_full_group_by
问题: 服务报错:incompatible with sql_mode=only_full_group_by,如下图所示: 分析: NLY_FULL_GROUP_BY是MySQL提供的一个sql_mo ...
- JavaScript 普通声明式函数
1.为什么需要函数 实现代码的复用.存在函数提升,且会在变量提升的上面; 2.函数的创建 js中函数语法: function 函数名(形参){ //函数体 } 调用时:函数名(形参) 注: (1) 形 ...
- 1.3 Junit4简介
1.Junit4框架 可用于单元测试,直接测试类中的方法 2.简单实用 a.导入Junit的jar包 b.熟悉Junit的执行顺序 c.写测试用例 d.利用断言,找bug 3.demo public ...
- 问题:unknown error: call function result missing 'value' 解决方法
问题:unknown error: call function result missing 'value' 页面也没有 填充信息 原因是:安装与chrome和对应的chromedriver版本问题 ...
- foundation DB问题
1. go get github.com/apple/foundationdb/bindings/go/src/fdb # github.com/apple/foundationdb/bindings ...
- 详解git pull和git fetch的区别
前言 在我们使用git的时候用的更新代码是git fetch,git pull这两条指令.但是有没有小伙伴去思考过这两者的区别呢?有经验的人总是说最好用git fetch+git merge,不建议用 ...
- OpenCL32 for mingw
OpenCL32 for MinGW 最新版本 2019.05.25 从 CUDA_Toolkit_10.1.168_425.25_win10 中提取的头文件和库文件: 链接: https://pan ...
- git 本地代码提交至远程master分支解决方法
git 提交代码,本地新建一个my分支,不从本地master分支直接上传,而是先从本地my分支上提交至本地master分支,然后本地master提交至远程master分支上.前提是远程只有一个mast ...
- Oracle 归档日志管理
一.Oracle日志介绍 1.Oracle日志分类 分三大类: Alert log files--警报日志,Trace files--跟踪日志(用户和进程)和 redo log ...