python进程类subprocess的一些操作方法例子

 更新时间:2014年11月22日 16:24:59   投稿:junjie  
这篇文章主要介绍了python进程类subprocess的一些操作方法例子,本文讲解了Popen、wait、poll、kill、communicate等方法的实际操作例子,需要的朋友可以参考下

subprocess.Popen用来创建子进程。

1)Popen启动新的进程与父进程并行执行,默认父进程不等待新进程结束。

复制代码 代码如下:

def TestPopen():
  import subprocess
  p=subprocess.Popen("dir",shell=True)
  for i in range(250) :
    print ("other things")

2)p.wait函数使得父进程等待新创建的进程运行结束,然后再继续父进程的其他任务。且此时可以在p.returncode中得到新进程的返回值。

复制代码 代码如下:

def TestWait():
  import subprocess
  import datetime
  print (datetime.datetime.now())
  p=subprocess.Popen("sleep 10",shell=True)
  p.wait()
  print (p.returncode)
  print (datetime.datetime.now())

3) p.poll函数可以用来检测新创建的进程是否结束。

复制代码 代码如下:

def TestPoll():
  import subprocess
  import datetime
  import time
  print (datetime.datetime.now())
  p=subprocess.Popen("sleep 10",shell=True)
  t = 1
  while(t <= 5):
    time.sleep(1)
    p.poll()
    print (p.returncode)
    t+=1
  print (datetime.datetime.now())

4) p.kill或p.terminate用来结束创建的新进程,在windows系统上相当于调用TerminateProcess(),在posix系统上相当于发送信号SIGTERM和SIGKILL。

复制代码 代码如下:

def TestKillAndTerminate():
    p=subprocess.Popen("notepad.exe")
    t = 1
    while(t <= 5):
      time.sleep(1)
      t +=1
    p.kill()
    #p.terminate()
    print ("new process was killed")

5) p.communicate可以与新进程交互,但是必须要在popen构造时候将管道重定向。

复制代码 代码如下:

def TestCommunicate():
  import subprocess
  cmd = "dir"
  p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  (stdoutdata, stderrdata) = p.communicate()
 
  if p.returncode != 0:
        print (cmd + "error !")
  #defaultly the return stdoutdata is bytes, need convert to str and utf8
  for r in str(stdoutdata,encoding='utf8' ).split("\n"):
    print (r)
  print (p.returncode)


def TestCommunicate2():
  import subprocess
  cmd = "dir"
  #universal_newlines=True, it means by text way to open stdout and stderr
  p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  curline = p.stdout.readline()

  while(curline != ""):
        print (curline)
        curline = p.stdout.readline()
  p.wait()
  print (p.returncode)

6) call函数可以认为是对popen和wait的分装,直接对call函数传入要执行的命令行,将命令行的退出code返回。

复制代码 代码如下:

def TestCall():
  retcode = subprocess.call("c:\\test.bat")
  print (retcode)

7)subprocess.getoutput 和 subprocess.getstatusoutput ,基本上等价于subprocess.call函数,但是可以返回output,或者同时返回退出code和output。

但是可惜的是好像不能在windows平台使用,在windows上有如下错误:'{' is not recognized as an internal or external command, operable program or batch file.

复制代码 代码如下:

def TestGetOutput():
  outp = subprocess.getoutput("ls -la")
  print (outp)

def TestGetStatusOutput():
  (status, outp) = subprocess.getstatusoutput('ls -la')
  print (status)
  print (outp)

8)总结

popen的参数,第一个为字符串(或者也可以为多个非命名的参数),表示你要执行的命令和命令的参数;后面的均为命名参数;shell=True,表示你前面的传入的命令将在shell下执行,如果你的命令是个可执行文件或bat,不需要指定此参数;stdout=subprocess.PIPE用来将新进程的输出重定向,stderr=subprocess.STDOUT将新进程的错误输出重定向到stdout,stdin=subprocess.PIPE用来将新进程的输入重定向;universal_newlines=True表示以text的方式打开stdout和stderr。

 其他的不推荐使用的模块:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

相关文章

  • ubuntu迁移anaconda到另外的目录(完美解决)

    ubuntu迁移anaconda到另外的目录(完美解决)

    本文主要介绍了ubuntu迁移anaconda到另外的目录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • 在Django的模板中使用认证数据的方法

    在Django的模板中使用认证数据的方法

    这篇文章主要介绍了在Django的模板中使用认证数据的方法,Django是最具人气的Python web开发框架,需要的朋友可以参考下
    2015-07-07
  • 利用Python实现K-Means聚类的方法实例(案例:用户分类)

    利用Python实现K-Means聚类的方法实例(案例:用户分类)

    k-means是发现给定数据集的k个簇的算法,也就是将数据集聚合为k类的算法,下面这篇文章主要给大家介绍了关于利用Python实现K-Means聚类的相关资料,需要的朋友可以参考下
    2022-05-05
  • 详解python如何通过numpy数组处理图像

    详解python如何通过numpy数组处理图像

    Numpy 是 Python 中科学计算的核心库,NumPy 这个词来源于 Numerical 和 Python 两个单词。它提供了一个高性能的多维数组对象,以及大量的库函数和操作,可以帮助程序员轻松地进行数值计算,广泛应用于机器学习模型、图像处理和计算机图形学、数学任务等领域
    2022-03-03
  • OpenCV哈里斯角检测|Harris Corner理论实践

    OpenCV哈里斯角检测|Harris Corner理论实践

    这篇文章主要为大家介绍了OpenCV哈里斯角检测|Harris Corner理论实践,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • python实现引用其他路径包里面的模块

    python实现引用其他路径包里面的模块

    这篇文章主要介绍了python实现引用其他路径包里面的模块,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • Python进程间通信Queue实例解析

    Python进程间通信Queue实例解析

    这篇文章主要介绍了Python进程间通信Queue实例解析,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Python中使用Pillow库生成立体文字的图像

    Python中使用Pillow库生成立体文字的图像

    在众多Python库中,Pillow库以其丰富的功能和易用性在图像处理领域脱颖而出,Pillow是Python领域中最基础且常用的图像处理库之一,,本文将详细介绍如何使用Python自动生成带有立体效果的文字,我们会逐步讲解输入文字、选择字体和颜色,并应用立体效果来生成最终图
    2025-03-03
  • Pytorch 如何查看、释放已关闭程序占用的GPU资源

    Pytorch 如何查看、释放已关闭程序占用的GPU资源

    这篇文章主要介绍了Pytorch 查看、释放已关闭程序占用的GPU资源的操作,具有很好的参考价值,希望对大家有所帮助。
    2021-05-05
  • 对python中的six.moves模块的下载函数urlretrieve详解

    对python中的six.moves模块的下载函数urlretrieve详解

    今天小编就为大家分享一篇对python中的six.moves模块的下载函数urlretrieve详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12

最新评论