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.*

相关文章

  • Python高级特性——详解多维数组切片(Slice)

    Python高级特性——详解多维数组切片(Slice)

    今天小编就为大家分享一篇Python高级特性——详解多维数组切片(Slice),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • Djang中静态文件配置方法

    Djang中静态文件配置方法

    这篇文章主要介绍Djang中静态文件配置方法的相关资料,django静态文件配置主要是为了让用户请求django服务器时能找到静态文件返回,需要的朋友可以参考下
    2015-07-07
  • Python入门之三角函数atan2()函数详解

    Python入门之三角函数atan2()函数详解

    这篇文章主要介绍了Python入门之三角函数atan2()函数详解,分享了其实例,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • tensorflow输出权重值和偏差的方法

    tensorflow输出权重值和偏差的方法

    本篇文章主要介绍了tensorflow输出权重值和偏差的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • django 扩展user用户字段inlines方式

    django 扩展user用户字段inlines方式

    这篇文章主要介绍了django 扩展user用户字段inlines方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • pyqt4教程之widget使用示例分享

    pyqt4教程之widget使用示例分享

    这篇文章主要介绍了pyqt4的widget使用示例,需要的朋友可以参考下
    2014-03-03
  • Python实现双X轴双Y轴绘图的示例详解

    Python实现双X轴双Y轴绘图的示例详解

    这篇文章主要介绍了如何利用fig.add_subplot和axes.twinx().twiny()方法实现双X轴双Y轴绘图,文中的示例代码讲解详细,快跟随小编一起动手尝试一下吧
    2022-04-04
  • Python OpenCV基于霍夫圈变换算法检测图像中的圆形

    Python OpenCV基于霍夫圈变换算法检测图像中的圆形

    这篇文章主要介绍了通过霍夫圈变换算法检测图像中的圆形,文中用到的函数为cv2.HoughCircles(),该函数可以很好地检测圆心。感兴趣的小伙伴可以了解一下
    2021-12-12
  • python Tkinter实例详解

    python Tkinter实例详解

    tkinter(Tk interface)是Python的标准GUl库,支持跨平台的GUl程序开发。tkinter适合小型的GUl程序编写,也特别适合初学者学习GUl编程,这篇文章主要介绍了python Tkinter详解,需要的朋友可以参考下
    2023-03-03
  • 小学生也能看懂的python语法之循环语句精解

    小学生也能看懂的python语法之循环语句精解

    这篇文章主要介绍了详解Python中的条件,循环语句,包括while循环for循环,循环语句是学习各个编程语言的最基本的基础知识,需要的朋友可以参考下
    2021-09-09

最新评论