python模块之subprocess模块级方法的使用


Posted in Python onMarch 26, 2019

subprocess.run()

运行并等待args参数指定的指令完成,返回CompletedProcess实例。

参数:(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)。除input, capture_output, timeout, check,其他参数与Popen构造器参数一致。

capture_output:如果设置为True,表示重定向stdout和stderr到管道,且不能再传递stderr或stdout参数,否则抛出异常。

input:input参数将作为子进程的标准输入传递给Popen.communicate()方法,必须是string(需要指定encoding或errors参数,或者设置text为True)或byte类型。非None的input参数不能和stdin参数一起使用,否则将抛出异常,构造Popen实例的stdin参数将指定为subprocess.PIPE。

timeout:传递给Popen.communicate()方法。

check:如果设置为True,进程执行返回非0状态码将抛出CalledProcessError异常。

# 源码

def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
  if input is not None:
    if 'stdin' in kwargs:
      raise ValueError('stdin and input arguments may not both be used.')
    kwargs['stdin'] = PIPE
  
  if capture_output:
    if ('stdout' in kwargs) or ('stderr' in kwargs):
      raise ValueError('stdout and stderr arguments may not be used '
               'with capture_output.')
    kwargs['stdout'] = PIPE
    kwargs['stderr'] = PIPE
  
  with Popen(*popenargs, **kwargs) as process:
    try:
      stdout, stderr = process.communicate(input, timeout=timeout)
    except TimeoutExpired:
      process.kill()
      stdout, stderr = process.communicate()
      raise TimeoutExpired(process.args, timeout, output=stdout,
                 stderr=stderr)
    except: # Including KeyboardInterrupt, communicate handled that.
      process.kill()
      # We don't call process.wait() as .__exit__ does that for us.
      raise
    retcode = process.poll()
    if check and retcode:
      raise CalledProcessError(retcode, process.args,
                   output=stdout, stderr=stderr)
  return CompletedProcess(process.args, retcode, stdout, stderr)

python3.5版本前,call(), check_all(), checkoutput()三种方法构成了subprocess模块的高级API。

subprocess.call()

运行并等待args参数指定的指令完成,返回执行状态码(Popen实例的returncode属性)。

参数:(*popenargs, timeout=None, **kwargs)。与Popen构造器参数基本相同,除timeout外的所有参数都将传递给Popen接口。

调用call()函数不要使用stdout=PIPE或stderr=PIPE,因为如果子进程生成了足量的输出到管道填满OS管道缓冲区,子进程将因不能从管道读取数据而导致阻塞。

# 源码
def call(*popenargs, timeout=None, **kwargs):
  with Popen(*popenargs, **kwargs) as p:
    try:
      return p.wait(timeout=timeout)
    except:
      p.kill()
      p.wait()
      raise

subprocess.check_call()

运行并等待args参数指定的指令完成,返回0状态码或抛出CalledProcessError异常,该异常的cmd和returncode属性可以查看执行异常的指令和状态码。

参数:(*popenargs, **kwargs)。全部参数传递给call()函数。

注意事项同call()

# 源码
def check_call(*popenargs, **kwargs):
  retcode = call(*popenargs, **kwargs)
  if retcode:
    cmd = kwargs.get("args")
    if cmd is None:
      cmd = popenargs[0]
    raise CalledProcessError(retcode, cmd)
  return 0

subprocess.check_output()

运行并等待args参数指定的指令完成,返回标准输出(CompletedProcess实例的stdout属性),类型默认是byte字节,字节编码可能取决于执行的指令,设置universal_newlines=True可以返回string类型的值。
如果执行状态码非0,将抛出CalledProcessError异常。

参数:(*popenargs, timeout=None, **kwargs)。全部参数传递给run()函数,但不支持显示地传递input=None继承父进程的标准输入文件句柄。

要在返回值中捕获标准错误,设置stderr=subprocess.STDOUT;也可以将标准错误重定向到管道stderr=subprocess.PIPE,通过CalledProcessError异常的stderr属性访问。

# 源码

def check_output(*popenargs, timeout=None, **kwargs):
  if 'stdout' in kwargs:
    raise ValueError('stdout argument not allowed, it will be overridden.')

  if 'input' in kwargs and kwargs['input'] is None:
    # Explicitly passing input=None was previously equivalent to passing an
    # empty string. That is maintained here for backwards compatibility.
    kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''

  return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
        **kwargs).stdout

subprocess模块还提供了python2.x版本中commands模块的相关函数。

subprocess.getstatusoutput(cmd)

实际上是调用check_output()函数,在shell中执行string类型的cmd指令,返回(exitcode, output)形式的元组,output(包含stderrstdout)是使用locale encoding解码的字符串,并删除了结尾的换行符。

# 源码
try:
  data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT)
  exitcode = 0
except CalledProcessError as ex:
  data = ex.output
  exitcode = ex.returncode
if data[-1:] == '\n':
  data = data[:-1]
return exitcode, data

subprocess.getoutput(cmd)

getstatusoutput()类似,但结果只返回output。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
利用Python中的输入和输出功能进行读取和写入的教程
Apr 14 Python
Django应用程序中如何发送电子邮件详解
Feb 04 Python
python中hashlib模块用法示例
Oct 30 Python
python+selenium识别验证码并登录的示例代码
Dec 21 Python
Python 批量合并多个txt文件的实例讲解
May 08 Python
完美解决在oj中Python的循环输入问题
Jun 25 Python
python pandas实现excel转为html格式的方法
Oct 23 Python
pyqt5移动鼠标显示坐标的方法
Jun 21 Python
pytorch多进程加速及代码优化方法
Aug 19 Python
python开发入门——set的使用
Sep 03 Python
python sleep和wait对比总结
Feb 03 Python
Python使用paramiko连接远程服务器执行Shell命令的实现
Mar 04 Python
详解Python数据可视化编程 - 词云生成并保存(jieba+WordCloud)
Mar 26 #Python
Python实现的矩阵转置与矩阵相乘运算示例
Mar 26 #Python
深度辨析Python的eval()与exec()的方法
Mar 26 #Python
详解Python locals()的陷阱
Mar 26 #Python
python 为什么说eval要慎用
Mar 26 #Python
Python eval的常见错误封装及利用原理详解
Mar 26 #Python
Python骚操作之动态定义函数
Mar 26 #Python
You might like
PHP3 safe_mode 失效漏洞
2006/10/09 PHP
php Xdebug 调试扩展的安装与使用.
2010/03/13 PHP
PHP开发中常见的安全问题详解和解决方法(如Sql注入、CSRF、Xss、CC等)
2014/04/21 PHP
如何让thinkphp在模型中自动完成session赋值小教程
2014/09/05 PHP
php实现改变图片直接打开为下载的方法
2015/04/14 PHP
Smarty foreach控制循环次数的一些方法
2015/07/01 PHP
掌握PHP垃圾回收机制详解
2019/03/13 PHP
dojo 之基础篇(二)之从服务器读取数据
2007/03/24 Javascript
非主流的textarea自增长实现js代码
2011/12/20 Javascript
深入学习jQuery Validate表单验证
2016/01/18 Javascript
微信小程序 引入es6 promise
2017/04/12 Javascript
JS返回顶部实例代码
2020/08/09 Javascript
前端html中jQuery实现对文本的搜索功能并把搜索相关内容显示出来
2017/11/14 jQuery
Vue替代marquee标签超出宽度文字横向滚动效果
2019/12/09 Javascript
javascript 使用sleep函数的常见方法详解
2020/04/26 Javascript
浅谈Vue使用Cascader级联选择器数据回显中的坑
2020/10/31 Javascript
python 中文字符串的处理实现代码
2009/10/25 Python
零基础学Python(一)Python环境安装
2014/08/20 Python
Python中的zipfile模块使用详解
2015/06/25 Python
Python中规范定义命名空间的一些建议
2016/06/04 Python
python利用跳板机ssh远程连接redis的方法
2019/02/19 Python
Python中最大递归深度值的探讨
2019/03/05 Python
Python学习笔记之列表和成员运算符及列表相关方法详解
2019/08/22 Python
PyQt5事件处理之定时在控件上显示信息的代码
2020/03/25 Python
Win10下用Anaconda安装TensorFlow(图文教程)
2020/06/18 Python
解决pyinstaller 打包exe文件太大,用pipenv 缩小exe的问题
2020/07/13 Python
python 线程的五个状态
2020/09/22 Python
Python 爬取淘宝商品信息栏目的实现
2021/02/06 Python
美国最大的骑马用品零售商:HorseLoverZ
2017/01/12 全球购物
希腊香水和化妆品购物网站:Parfimo.gr
2019/10/03 全球购物
.NET方向面试题
2014/11/20 面试题
计算机本科生自荐信
2013/10/15 职场文书
医药公司开票员岗位职责
2015/04/15 职场文书
董事长致辞
2015/07/29 职场文书
opencv检测动态物体的实现
2021/07/21 Python
 python中的元类metaclass详情
2022/05/30 Python