国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python subprocess模塊詳細解讀

2020-01-04 16:02:08
字體:
來源:轉載
供稿:網友

本文研究的主要是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 subprocessimport osclass Shell(object) : def runCmd(self, cmd) :  res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  sout ,serr = res.communicate()   return res.returncode, sout, serr, res.pidshell = Shell()fp = open('c://test//ip.txt', 'r')ipList = fp.readlines()fp.close()fp = open('c://test//ping.txt', 'a')print ipListfor 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()

執行結果:

python,subprocess,模塊,python的subprocess,python執行subprocess

進程通信實例2

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

import subprocessclass Shell(object) : def runCmd(self, cmd) :  res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  sout ,serr = res.communicate()     return res.returncode, sout, serr, res.pidshell = 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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 五寨县| 东山县| 分宜县| 瑞金市| 合肥市| 晋江市| 稷山县| 桐梓县| 安图县| 云浮市| 大姚县| 东兴市| 绥滨县| 彭泽县| 双峰县| 宜都市| 四会市| 昌邑市| 肇东市| 鹤岗市| 莱州市| 环江| 简阳市| 平阳县| 定边县| 荣昌县| 克山县| 惠水县| 乌审旗| 龙口市| 湖北省| 灵璧县| 凤阳县| 卓资县| 尉犁县| 丹巴县| 华池县| 福鼎市| 临湘市| 云安县| 临夏县|