美文网首页
21.subprocess模块

21.subprocess模块

作者: 哈哈大圣 | 来源:发表于2019-12-25 22:36 被阅读0次

subprocess模块

1). 概述

  1. 系统命令调用模块
  2. 导入方式
import subprocess

2). run()方法

  1. 官方推荐的执行方法:同步方法
  2. 与之还有一个call方法,使用较少
  3. 执行案例
a = subprocess.run(["df","-h"], stderr = subprocess.PIPE, 
                    stdout = subprocess.PIPE, check=True)
  1. 签名解释

    • ["df","-h"]命令参数,开启一个进程
    • stderr = subprocess.PIPE 如果报错,通过管道接受程序执行的错误信息 (命令参数就不能写管道符号)
    • stdout = subprocess.PIPE 通过管道接受程序执行结果 (命令参数就不能写管道符号)
    • check = True 如果程序执行出现错误,返回一个非0值,解释器就报错
  2. 其他方式

a = subprocess.run("df -h | grep disk1",stderr = subprocess.PIPE,
                    stdout = subprocess.PIPE,check=True,shell = True)

加一个shell = True,命令行参数不用列表的形式,直接写shell下执行的格式,就是直接将内容交给shell,不通过解释器进行拼接

3). Popen()方法

  1. Popen 将run与call进行封装:异步方法
  2. 使用案例
a = subprocess.Popen(
    "sleep 2",
    shell = True, 
    cwd="/temp",
    stdout = subprocess.PIPE,
    preexec_fn=sayhi)
    
a.stdout.read()
  1. 参数解释
    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • shell:同上
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object,比如函数的名字),它将在子进程运行之前被调用
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
  1. Popen调用后会返回一个对象,假设为a对象,有如下API
    • a.poll():Check if child process has terminated. Returns returncode
    • a.wait():Wait for child process to terminate. Returns returncode attribute.
    • a.terminate():终止所启动的进程 (不会强制终止,只是发一个终止信号)
    • a.kill():杀死所启动的进程,强制终止
    • a.communicate(b'22'):与启动的进程交互,发送数据到stdin,并从stdout接收输出,然后等待任务结束
    • a.send_signal(signal.xxx):发送系统信号
    • a.pid:拿到所启动进程的进程号

相关文章

  • 21.subprocess模块

    subprocess模块 1). 概述 系统命令调用模块 导入方式 2). run()方法 官方推荐的执行方法:同...

  • python常用模块!!

    os模块: stat模块: sys模块: hashlib,md5模块: random模块: types模块: at...

  • 2018-08-19

    Angular 2 技能图谱 模块 自定义模块 根模块 特性模块 共享模块 核心模块 内置模块 Applicati...

  • 【时间管理100讲】精髓全在这里啦

    理论模块 精力管理。 行动管理。 学习模块。 高空模块。 反思模块。 运动模块。 阅读模块。 旅行模块。 人际关系...

  • python基础学习(三)

    常用模块 String模块 数学模块 随机模块 OS模块 os.path模块 re模块 常用函数及操作 列表操作 ...

  • day10-异常处理和pygame显示

    一、异常处理 1.模块 导入模块(自定义模块,第三方模块)import 模块 ---->模块.内容from 模块 ...

  • 重点知识复习(异常处理)

    1.模块 导入模块(自定义模块,第三方模块,系统其他模块)import 模块 ----> 模块.内容from 模...

  • Python常用模块

    Python常用模块之time模块 Python常用模块之os模块 Python常用模块之sys模块 Python...

  • nodejs-模块

    nodejs模块 一、nodejs模块分类 1.核心模块 Core Module、内置模块、原生模块 fs模块 p...

  • Python不同网络模块网页源代码的获取

    requests模块 或者使用 selenium模块 BeautifulSoup模块 urllib模块

网友评论

      本文标题:21.subprocess模块

      本文链接:https://www.haomeiwen.com/subject/pnmhoctx.html