subprocess
subprocess是Python 2.4中新增的一個模塊,它允許你生成新的進程,連接到它們的 input/output/error 管道,並獲取它們的返回(狀態)碼。這個模塊的目的在於替換幾個舊的模塊和方法,如:
os.system
os.spawn*
常用參數
1)、args可以是字符串或者序列類型(如:list,元組),用於指定進程的可執行文件及其參數。如果是序列類型,第一個元素通常是可執行文件的路徑。我們也可以顯式的使用executeable參數來指定可執行文件的路徑。
2)、bufsize:指定緩衝。0 無緩衝,1 行緩衝,其他 緩衝區大小,負值 系統緩衝(全緩衝)
3)、stdin, stdout, stderr分別表示程序的標準輸入、輸出、錯誤句柄。他們可以是PIPE,文件描述符或文件對象,也可以設置為None,表示從父進程繼承。
4)、preexec_fn只在Unix平臺下有效,用於指定一個可執行對象(callable object),它將在子進程運行之前被調用。
5)、Close_sfs:在windows平臺下,如果close_fds被設置為True,則新創建的子進程將不會繼承父進程的輸入、輸出、錯誤管道。我們不能將close_fds設置為True同時重定向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。
6)、shell設為true,程序將通過shell來執行。
7)、cwd用於設置子進程的當前目錄
8)、env是字典類型,用於指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。
9)、Universal_newlines:不同操作系統下,文本的換行符是不一樣的。如:windows下用'/r/n'表示換,而Linux下用'/n'。如果將此參數設置為True,Python統一把這些換行符當作'/n'來處理。startupinfo與createionflags只在windows下用效,它們將被傳遞給底層的CreateProcess()函數,用於設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等。
10)、startupinfo與createionflags只在windows下有效,它們將被傳遞給底層的CreateProcess()函數,用於設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等。
Popen方法
1)、Popen.poll():用於檢查子進程是否已經結束。設置並返回returncode屬性。
2)、Popen.wait():等待子進程結束。設置並返回returncode屬性。
3)、Popen.communicate(input=None):與子進程進行交互。向stdin發送數據,或從stdout和stderr中讀取數據。可選參數input指定發送到子進程的參數。Communicate()返回一個元組:(stdoutdata, stderrdata)。注意:如果希望通過進程的stdin向其發送數據,在創建Popen對象的時候,參數stdin必須被設置為PIPE。同樣,如果希望從stdout和stderr獲取數據,必須將stdout和stderr設置為PIPE。
4)、Popen.send_signal(signal):向子進程發送信號。
5)、Popen.terminate():停止(stop)子進程。在windows平臺下,該方法將調用Windows API TerminateProcess()來結束子進程。
6)、Popen.kill():殺死子進程。
7)、Popen.stdin:如果在創建Popen對象是,參數stdin被設置為PIPE,Popen.stdin將返回一個文件對象用於策子進程發送指令。否則返回None。
8)、Popen.stdout:如果在創建Popen對象是,參數stdout被設置為PIPE,Popen.stdout將返回一個文件對象用於策子進程發送指令。否則返回None。
9)、Popen.stderr:如果在創建Popen對象是,參數stdout被設置為PIPE,Popen.stdout將返回一個文件對象用於策子進程發送指令。否則返回None。
10)、Popen.pid:獲取子進程的進程ID。
11)、Popen.returncode:獲取進程的返回值。如果進程還沒有結束,返回None。
12)、subprocess.call(*popenargs, **kwargs):運行命令。該函數將一直等待到子進程運行結束,並返回進程的returncode。文章一開始的例子就演示了call函數。如果子進程不需要進行交互,就可以使用該函數來創建。
13)、subprocess.check_call(*popenargs, **kwargs):與subprocess.call(*popenargs, **kwargs)功能一樣,只是如果子進程返回的returncode不為0的話,將觸發CalledProcessError異常。在異常對象中,包括進程的returncode信息。
實例一
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/14 11:07
# @Author : CaiChangEn
# @Email : [email protected]
# @Software: PyCharm
import subprocess
cmd=str(input('請輸入要執行的命令:'))
print(cmd)
s=subprocess.Popen(cmd,shell=True, # 執行客戶端發送來的命令
stdout=subprocess.PIPE, # 將正確輸出放入標準輸出管道
stdin=subprocess.PIPE, # 將輸入放入標準輸入管道
stderr=subprocess.PIPE) # 將錯誤輸出放入標準錯誤輸出管道
stdoutinfo,stderrinfo=s.communicate() #communicate返回一個元祖,(stdout,stderr)
print((stdoutinfo.decode('gbk')) # 打印返回的stdout
print(stderrinfo.decode('gbk')) # 打印返回的stderr
實例二
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/14 11:07
# @Author : CaiChangEn
# @Email : [email protected]
# @Software: PyCharm
import subprocess
while True:
cmd=str(input('請輸入要執行的命令:'))
res=subprocess.Popen(cmd,shell=True, # 執行客戶端發送來的命令
stdout=subprocess.PIPE, # 將正確輸出放入標準輸出管道
stdin=subprocess.PIPE, # 將輸入放入標準輸入管道
stderr=subprocess.PIPE) # 將錯誤輸出放入標準錯誤輸出管道
stderr=res.stderr.read() # 錯誤的結果賦值給stderr
stdout=res.stdout.read() # 正確的結果賦值給stdout
if not stderr and not stdout: # 有的命令沒有返回值,就走該判斷
print('執行成功')
elif stderr: # 如果stderr有值就打印錯誤信息,如果沒有就打印返回值
print('錯誤信息:%s' %stderr.decode('gbk'))
else:
print('返回信息:%s' %stdout.decode('gbk'))
閱讀更多 動漫資深愛好者和IT 的文章