我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python2有os.system,

>>> os.system('uname') Darwin

  除了os.system可以调用系统命令,,commands,popen2等也可以,比较乱,于是官方推出了subprocess,目地是提供统一的模块来实现对系统命令或脚本的调用

  The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

  • os.system
  • os.spawn*

  The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.

三种执行命令的方法

  • subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推荐

  • subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面实现的内容差不多,另一种写法

  • subprocess.Popen() #上面各种方法的底层封装

run()方法

Run command with arguments and return a CompletedProcess instance.The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.

If check is True and the exit code was non-zero, it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute, and output & stderr attributes if those streams were captured.

If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised.

The other arguments are the same as for the Popen constructor.

1 标准写法
2
3 subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)
4 涉及到管道|的命令需要这样写
5
6 subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析

call()方法

#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])#执行命令,如果命令结果为0,就正常返回,否则抛异常
>>> subprocess.check_call(["ls", "-l"])
0#接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')#接收字符串格式命令,并返回结果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'#执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'

Popen()方法

常用参数:

  • args:shell命令,可以是字符串或者序列类型(如:list,元组)
  • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
  • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
  • shell:同上
  • cwd:用于设置子进程的当前目录
  • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。

下面这2条语句执行会有什么区别?

a=subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE)
a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)

区别是Popen会在发起命令后立刻返回,而不等命令执行结果。这样的好处是什么呢?

如果你调用的命令或脚本 需要执行10分钟,你的主程序不需卡在这里等10分钟,可以继续往下走,干别的事情,每过一会,通过一个什么方法来检测一下命令是否执行完成就好了。

Popen调用后会返回一个对象,可以通过这个对象拿到命令执行结果或状态等,该对象有以下方法

poll()

Check if child process has terminated. Returns returncode

wait()

Wait for child process to terminate. Returns returncode attribute.

terminate()终止所启动的进程Terminate the process with SIGTERM

kill() 杀死所启动的进程 Kill the process with SIGKILL

communicate()与启动的进程交互,发送数据到stdin,并从stdout接收输出,然后等待任务结束

>>> a = subprocess.Popen('python3 guess_age.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True) >>> a.communicate(b'22') (b'your guess:try bigger\n', b'') 

send_signal(signal.xxx)发送系统信号

pid 拿到所启动进程的进程号

转载于:https://www.cnblogs.com/wenyule/p/py-subprocess.html

subprocess 模块相关推荐

  1. python subprocess模块 命令执行

    subprocess模块中定义了一个Popen类,通过它可以来创建进程,并与其进行复杂的交互.查看一下它的构造函数: __init__(self, args, bufsize=0, executabl ...

  2. Python subprocess模块

    subprocess subprocess模块介绍 subprocess模块是一个可以将系统内的命令结果赋值给变量并打印, 还可以输出命令执行状态,subprocess可以单独将 命令输出结果与执行状 ...

  3. python subprocess 模块

    subprocess 模块中有一个功能Popen , 可以在代码中调用系统的命令 其功能比os.system 更加强大 代码示例: command = 'python -u %s/generalMak ...

  4. Python常用模块之subprocess模块

    当我们需要调用系统的命令的时候,最先考虑的os模块.用os.system()和os.popen()来进行操作. 但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出 ...

  5. python3中使用subprocess模块执行外部命令

    一. subprocess模块介绍 subprocess模块可以替代os模块下的os.system和os.popen等操作方法 subprocess模块在python2和python3上的使用上有一定 ...

  6. Python之路(第二十篇) subprocess模块

    一.subprocess模块 subprocess英文意思:子进程 那什么是进程呢? (一)关于进程的相关理论基础知识 进程是对正在运行程序的一个抽象,进程的概念起源于操作系统,是操作系统最核心的概念 ...

  7. python的subprocess模块执行shell命令

    subprocess模块可以允许我们执行shell命令 一般来说,使用run()方法就可以满足大部分情况 使用run执行shell命令 In [5]: subprocess.run('echo &qu ...

  8. 模拟ssh, hashlib模块, struct模块, subprocess模块

    一. 模拟ssh # ===================================== 服务器端 =====================================import so ...

  9. python subprocess communicate_Python中的Subprocess模块

    以前我一直用os.system()处理一些系统管理任务,因为我认为那是运行linux命令最简单的方式. 我们能从Python官方文档里读到应该用subprocess 模块来运行系统命令.subproc ...

  10. Python之subprocess模块

    subprocess模块允许你启动一个新的进程,连接输入/输出/错误的管道,  获得子进程的返回码.这个模块目标是代替一些老的模块,比如os.system和os.spawn. 0x01 常见subpr ...

最新文章

  1. Openssl私建CA
  2. 2010 .NET面试题整理之基础篇
  3. Systemd:再一次的,回归第一进程
  4. CKO将成为企业发展的军师--转自世界名人网
  5. c语言画图 钟表模拟程序,图形模拟时钟C语言课程设计
  6. c command语言学例子,乔姆斯基语言学理论发展史研究
  7. C#程序集Assembly学习随笔(第一版)_AX
  8. scala基础之特质trait
  9. 详解《云原生架构白皮书》,附下载链接
  10. 51单片机矩阵按键模块
  11. cwe_checker 二进制静态漏洞检测工具的安装与使用
  12. uni-app 文件下载
  13. Jboot v1.4.0 新增分库分表及 websocket 相关 demo
  14. 学习嵌入式Linux开发——RK3288开发板学习规划及目标
  15. Spring Bean作用域与生命周期
  16. RR 时间片轮转算法 (java)
  17. Android Q适配攻略(一)(图标适配)
  18. Data Structures and Algorithms (English) - 6-10 Sort Three Distinct Keys(30 分)
  19. 假设检验:一个总体参数的检验、总体方差检验、两个总体参数的检验和两个总体方差的检验
  20. vant d的地址组件中文操作手册

热门文章

  1. python3爬虫实例-python3.7简单的爬虫实例详解
  2. python在哪里学比较好-Python学习在哪里比较好?
  3. python编写程序-在线python编程
  4. python3.7和3.8的区别-Python 3.8 有什么新变化
  5. redis中的lua
  6. 企业应用架构模式学习笔记
  7. UVa1450 Airport(二分法)
  8. Java中的抽象类和方法
  9. Python分页组件
  10. 吴恩达机器学习笔记7-数据绘制