Python subprocess模組解析

2021-07-05 12:17:25 字數 4753 閱讀 4190

在學習這個模組前,我們先用python的help()函式檢視一下subprocess模組是幹嘛的:

description

this module allows you to spawn processes, connect to their

input/output/error pipes, and obtain their return codes.

即允許你去建立乙個新的程序讓其執行另外的程式,並與它進行通訊,獲取標準的輸入、標準輸出、標準錯誤以及返回碼等。

注意:使用這個模組之前要先引入該模組。

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,子程序的環境變數將從父程序繼承而來。

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的引數,表示將標準錯誤通過標準輸出流輸出。

1、popen.pid

獲取子程序的程序id。

2、popen.returncode

獲取程序的返回碼。如果程序未結束,將返回none。

3、communicate(input=none)

官方解釋:

interact with

process: send data to

stdin. read data from

stdout

andstderr, until

end-of-file is

reached. wait

forprocess

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

theprocess

傳送訊號給子程序。

7、terminate()

terminates the

process

終止子程序。windows下將呼叫windows api terminateprocess()來結束子程序。

8、kill()

官方文件對這個函式的解釋跟terminate()是一樣的,表示殺死子程序。

開啟乙個只有ip位址的文字檔案,讀取其中的ip,然後進行ping操作,並將ping結果寫入ping.txt檔案中。

首先建立乙個子程序res,傳入要執行的shell命令,並獲得標準輸出流、返回碼等。

import subprocess

import os

class

shell

(object) :

defruncmd

(self, cmd) :

res = subprocess.popen(cmd, shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout)

sout ,serr = res.communicate()

return res.returncode, sout, serr, res.pid

shell = shell()

fp = open('c:\\test\\ip.txt', 'r')

iplist = fp.readlines()

fp.close()

fp = open('c:\\test\\ping.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()

執行結果:

命令互動,不斷從鍵盤接受命令執行,給出執行結果,直到使用者輸入exit或者bye退出命令互動。

import subprocess

class

shell

(object) :

defruncmd

(self, cmd) :

res = subprocess.popen(cmd, shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout)

sout ,serr = res.communicate()

return res.returncode, sout, serr, 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 2.4開始,python引入subprocess模組來管理子程序,以取代一些舊模組的方法 如 os.system os.spawn os.popen popen2.commands.不但可以呼叫外部的命令作為子程序,而且可以連線到子程序的input output error管道,獲取...

python subprocess模組 學習筆記

subprocess允許你啟動乙個新的程序並與其通訊。subprocess模組中只定義了乙個類,popen。subprocess.popen args,bufsize 0,executable none,stdin none,stdout none,stderr none,preexec fn no...

Python subprocess模組學習總結

從python 2.4開始,python引入subprocess模組來管理子程序,以取代一些舊模組的方法 如 os.system os.spawn os.popen popen2.commands.不但可以呼叫外部的命令作為子程序,而且可以連線到子程序的input output error管道,獲取...