subprocess.Popen

这个模块主要就提供一个类Popen:

class subprocess.Popen( args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0)

这堆东西真让人抓狂:

args

字符串或者列表

bufsize

0 无缓冲
1 行缓冲
其他正值 缓冲区大小
负值 采用默认系统缓冲(一般是全缓冲)

executable

一般不用吧,args字符串或列表第一项表示程序名

stdin
stdout
stderr

None 没有任何重定向,继承父进程
PIPE 创建管道
文件对象
文件描述符(整数)
stderr 还可以设置为 STDOUT

preexec_fn

钩子函数, 在fork和exec之间执行。(unix)

close_fds

unix 下执行新进程前是否关闭0/1/2之外的文件
windows下不继承还是继承父进程的文件描述符

shell

为真的话
unix下相当于args前面添加了 "/bin/sh“ ”-c”
window下,相当于添加"cmd.exe /c"

cwd

设置工作目录

env

设置环境变量

universal_newlines

各种换行符统一处理成 '\n'

startupinfo

window下传递给CreateProcess的结构体

creationflags

windows下,传递CREATE_NEW_CONSOLE创建自己的控制台窗口

  • 当初最感到困扰的就是 args 参数。可以是一个字符串,可以是一个列表。
subprocess.Popen(["gedit","abc.txt"])
subprocess.Popen("gedit abc.txt")

这两个之中,后者将不会工作。因为如果是一个字符串的话,必须是程序的路径才可以。(考虑unix的api函数 exec,接受的是字符串列表)

  • 但是下面的可以工作
subprocess.Popen("gedit abc.txt", shell=True)

这是因为它相当于

subprocess.Popen(["/bin/sh", "-c", "gedit abc.txt"])

都成了sh的参数,就无所谓了

  • 在Windows下,下面的却又是可以工作的
subprocess.Popen(["notepad.exe", "abc.txt"])
subprocess.Popen("notepad.exe abc.txt")

这是由于windows下的api函数CreateProcess接受的是一个字符串。即使是列表形式的参数,也需要先合并成字符串再传递给api函数。

  • 类似上面
subprocess.Popen("notepad.exe abc.txt" shell=True)

等价于

subprocess.Popen("cmd.exe /C "+"notepad.exe abc.txt" shell=True)

subprocess.call*

模块还提供了几个便利函数(这本身也算是很好的Popen的使用例子了)

  • call() 执行程序,并等待它完成
def call(*popenargs, **kwargs):
return Popen(*popenargs, **kwargs).wait()
  • check_call() 调用前面的call,如果返回值非零,则抛出异常
def check_call(*popenargs, **kwargs):
retcode = call(*popenargs, **kwargs)
if retcode:
cmd = kwargs.get("args")
raise CalledProcessError(retcode, cmd)
return 0
  • check_output() 执行程序,并返回其标准输出
def check_output(*popenargs, **kwargs):
process = Popen(*popenargs, stdout=PIPE, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
raise CalledProcessError(retcode, cmd, output=output)
return output

Popen对象

该对象提供有不少方法函数可用。而且前面已经用到了wait()/poll()/communicate()

poll()

检查是否结束,设置返回值

wait()

等待结束,设置返回值

communicate()

参数是标准输入,返回标准输出和标准出错

send_signal()

发送信号 (主要在unix下有用)

terminate()

终止进程,unix对应的SIGTERM信号,windows下调用api函数TerminateProcess()

kill()

杀死进程(unix对应SIGKILL信号),windows下同上

stdin
stdout
stderr

参数中指定PIPE时,有用

pid

进程id

returncode

进程返回值

参考

python学习之subprocess模块的更多相关文章

  1. python学习之-- subprocess模块

    subprocess 模块 功能:用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值.它用来代替多个旧模块和函数: os.system os.spawn* os.popen ...

  2. python笔记之subprocess模块

    python笔记之subprocess模块 [TOC] 从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spaw ...

  3. Python学习 Part4:模块

    Python学习 Part4:模块 1. 模块是将定义保存在一个文件中的方法,然后在脚本中或解释器的交互实例中使用.模块中的定义可以被导入到其他模块或者main模块. 模块就是一个包含Python定义 ...

  4. python学习之argparse模块

    python学习之argparse模块 一.简介: argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块.argparse模块的作用是用于解析命令行 ...

  5. Python学习day19-常用模块之re模块

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  6. Python学习day18-常用模块之NumPy

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  7. python学习笔记五 模块下(基础篇)

    shevle 模块 扩展pickle模块... 1.潜在的陷进 >>> import shelve>>> s = shelve.open("nb" ...

  8. python学习之random模块

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  9. python 学习day5(模块)

    一.模块介绍 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能 ...

随机推荐

  1. java:I/O 字节流和字符流

    字节流 InputStream和OutputStream的子类:FileInputStream 和 FileOutputStream 方法: int read(byte[] b,int off,int ...

  2. 机器人学 —— 轨迹规划(Introduction)

    轨迹规划属于机器人学中的上层问题,其主要目标是计划机器人从A移动到B并避开所有障碍的路线. 1.轨迹计划的对象 轨迹规划的对象是map,机器人通过SLAM获得地map后,则可在地图中选定任意两点进行轨 ...

  3. Java知识积累——单元测试和JUnit(一)

    说起单元测试,刚毕业或者没毕业的人可能大多停留在课本讲述的定义阶段,至于具体是怎么定义的,估计也不会有太多人记得.我们的教育总是这样让人“欣 慰”.那么什么是单元测试呢?具体科学的定义咱就不去关心了, ...

  4. Unique Encryption Keys (思维题 预处理)

    题目 题意:给m个数字, q次询问, 询问b到e之间如果有重复数字就输出, 没有就输出OK 思路:用f[i]数组 记录从i开始向后最近的有重复数字的 位置, 如 1 3 2 2, 则f[1] = 4; ...

  5. freemarker中判断对象是否为空

    <#if xxx?exists> 或则 <#if xxx??>两个问号??最简单方便

  6. Android之 学习路线

    第一阶段:Java面向对象编程 1.Java基本数据类型与表达式,分支循环.  2.String和StringBuffer的使用.正则表达式.  3.面向对象的抽象,封装,继承,多态,类与对象,对象初 ...

  7. ti processor sdk linux am335x evm /bin/unshallow-repositories.sh hacking

    #!/bin/bash # # ti processor sdk linux am335x evm /bin/unshallow-repositories.sh hacking # 说明: # 本文主 ...

  8. python - os.path,路径相关操作

    python处理系统路径的相关操作: # -*- coding: utf-8 -*- import os # 属性 print '__file__: %s' % __file__ # 绝对路径(包含文 ...

  9. 【DFS+堆的二叉树结构】15轻院校赛-J-堆

    [题目链接:J-堆] 1734: 堆 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 239  Solved: 113 SubmitStatusWeb B ...

  10. Android启动activity的4种模式(standard、singleTop、singleTask、singleINstance)

    在AndroidManifest.xml中配置activity时,android:launchMode属性会指定启动activity的模式,有四种: standard singleTop single ...