加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python subprocess模块详细解读

发布时间:2020-12-17 07:29:26 所属栏目:Python 来源:网络整理
导读:本文研究的主要是Python subprocess模块的相关内容,具体如下。 在学习这个模块前,我们先用Python的help()函数查看一下subprocess模块是干嘛的: DESCRIPTION This module allows you to spawn processes,connect to their input/output/error pipes,and ob

本文研究的主要是Python subprocess模块的相关内容,具体如下。

在学习这个模块前,我们先用Python的help()函数查看一下subprocess模块是干嘛的:

DESCRIPTION
This module allows you to spawn processes,connect to their
input/output/error pipes,and obtain their return codes.

即允许你去创建一个新的进程让其执行另外的程序,并与它进行通信,获取标准的输入、标准输出、标准错误以及返回码等。
注意:使用这个模块之前要先引入该模块。

Popen类

subprocess模块中定义了一个Popen类,通过它可以来创建进程,并与其进行复杂的交互。查看一下它的构造函数:

__init__(self,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:args should be a string,or a sequence of program arguments.也就是说必须是一个字符串或者序列类型(如:字符串、list、元组),用于指定进程的可执行文件及其参数。如果是一个序列类型参数,则序列的第一个元素通常都必须是一个可执行文件的路径。当然也可以使用executeable参数来指定可执行文件的路径。

stdin,stdout,stderr:分别表示程序的标准输入、标准输出、标准错误。有效的值可以是PIPE,存在的文件描述符,存在的文件对象或None,如果为None需从父进程继承过来,stdout可以是PIPE,表示对子进程创建一个管道,stderr可以是STDOUT,表示标准错误数据应该从应用程序中捕获并作为标准输出流stdout的文件句柄。

shell:如果这个参数被设置为True,程序将通过shell来执行。

env:它描述的是子进程的环境变量。如果为None,子进程的环境变量将从父进程继承而来。

创建Popen类的实例对象

res = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

cmd:标准像子进程传入需要执行的shell命令,如:ls -al

subprocess.PIPE:在创建Popen对象时,subprocess.PIPE可以初始化为stdin,stdout或stderr的参数,表示与子进程通信的标准输入流,标准输出流以及标准错误。

subprocess.STDOUT:作为Popen对象的stderr的参数,表示将标准错误通过标准输出流输出。

Popen类拥有的方法及属性

1、Popen.pid

获取子进程的进程ID。

2、Popen.returncode

获取进程的返回码。如果进程未结束,将返回None。

3、communicate(input=None)

官方解释:

Interact with process: Send data to stdin. Read data from
stdout and stderr,until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process,or None,if no data
should be sent to the child.

communicate() returns a tuple (stdout,stderr).

与子进程进行交互,像stdin发送数据,并从stdout和stderr读出数据存在一个tuple中并返回。
参数input应该是一个发送给子进程的字符串,如果未指定数据,将传入None。

4、poll()

检查子进程是否结束,并返回returncode属性。

5、wait()

Wait for child process to terminate. Returns returncode attribute.

等待子进程执行结束,并返回returncode属性,如果为0表示执行成功。

6、send_signal( sig)

Send a signal to the process

发送信号给子进程。

7、terminate()

Terminates the process

终止子进程。windows下将调用Windows API TerminateProcess()来结束子进程。

8、kill()

官方文档对这个函数的解释跟terminate()是一样的,表示杀死子进程。

进程通信实例1

打开一个只有ip地址的文本文件,读取其中的ip,然后进行ping操作,并将ping结果写入ping.txt文件中。
首先创建一个子进程res,传入要执行的shell命令,并获得标准输出流、返回码等。

import subprocess
import os
class Shell(object) :
 def runCmd(self,cmd) :
  res = subprocess.Popen(cmd,stderr=subprocess.STDOUT)
  sout,serr = res.communicate() 
  return res.returncode,sout,serr,res.pid

shell = Shell()
fp = open('c:testip.txt','r')
ipList = fp.readlines()
fp.close()
fp = open('c:testping.txt','a')
print ipList
for i in ipList :
 i = i.strip()
 result = shell.runCmd('ping ' + i)
 if result[0] == 0 :
  w = i + ' : 0'
  fp.write(w + 'n')
 else :
  w = i + ' : 1'
  fp.write(w + 'n')

fp.close()

执行结果:

进程通信实例2

命令交互,不断从键盘接受命令执行,给出执行结果,直到用户输入exit或者bye退出命令交互。

import subprocess
class Shell(object) :
 def runCmd(self,serr = res.communicate()   
  return res.returncode,res.pid

shell = Shell()
while 1 :
 input = raw_input('>')
 if input == 'exit' or input == 'bye' :
  break
 else :
  result = shell.runCmd(input)
  print "返回码:",result[0]
  print "标准输出:",result[1]
  print "标准错误:",result[2]

在Windows上也可以使用os.system()这个函数来执行一些dos命令,但是这个命令只能拿到返回码,拿不到标准输出,标准错误,所以通常使用的subprocess模块中的Popen类来实现。

总结

以上就是本文关于Python subprocess模块详细解读的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

您可能感兴趣的文章:

  • Python中subprocess模块用法实例详解
  • Python下的subprocess模块的入门指引
  • Python 创建子进程模块subprocess详解
  • Python的subprocess模块总结
  • Python subprocess模块学习总结

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读