侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   349

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(包含stderr和stdout)是使用locale encoding解码的字符串,并删除了结尾的换行符。

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

subprocess.getoutput(cmd)

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

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


  • 上一条:
    Python3实现的回文数判断及罗马数字转整数算法示例
    下一条:
    详解Python数据可视化编程 - 词云生成并保存(jieba+WordCloud)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客