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

yipeiwu_com6年前Python基础

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实现的微信好友数据分析

基于Python实现的微信好友数据分析

最近微信迎来了一次重要的更新,允许用户对”发现”页面进行定制。不知道从什么时候开始,微信朋友圈变得越来越复杂,当越来越多的人选择”仅展示最近三天的朋友圈”,大概连微信官方都是一脸的无可奈...

Python.append()与Python.expand()用法详解

如下所示: alist=[1,2]] >>>[1,2] alist.append([3,4]) >>>[1, 2, [3, 4]] alist...

Python猴子补丁知识点总结

属性在运行时的动态替换,叫做猴子补丁(Monkey Patch)。 为什么叫猴子补丁 属性的运行时替换和猴子也没什么关系,关于猴子补丁的由来网上查到两种说法: 1.这个词原来为Guerr...

python版本的仿windows计划任务工具

python版本的仿windows计划任务工具

计划任务工具-windows 计划任务工具根据自己设定的具体时间,频率,命令等属性来规定所要执行的计划。 效果图 代码 # -*- coding: utf-8 -*- """ M...

利用Python实现Shp格式向GeoJSON的转换方法

利用Python实现Shp格式向GeoJSON的转换方法

一、简介 Shp格式是GIS中非常重要的数据格式,主要在Arcgis中使用,但在进行很多基于网页的空间数据可视化时,通常只接受GeoJSON格式的数据,众所周知JSON(JavaScri...