Python3中常用模塊-subprocess模塊

 目錄

1:獲取模塊幫助文檔

2:基本操作方法

2.1:subprocess.call

2.2:subprocess.check_call

2.3:subprocess.check_output

2.4:subprocess.getoutput

2.5:subprocess.getstatusoutput

2.6:subprocess.run

2.7:subprocess.Popen


subprocess 模塊允許你生成新的進程,連接它們的輸入、輸出、錯誤管道,並且獲取它們的返回碼。此模塊打算代替一些老舊的模塊與功能:
 os.system
 os.spawn*

1:獲取模塊幫助文檔

# encoding=gbk
import  subprocess

print(subprocess.__doc__)

print(dir(subprocess))

for item in dir(subprocess):
    print(item)


print(help(subprocess.run))
print(help(subprocess.Popen))
print(subprocess.__doc__) 返回值如下:
This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.

For a complete description of this module see the Python documentation.

Main API
========
run(...): Runs a command, waits for it to complete, then returns a
          CompletedProcess instance.
Popen(...): A class for flexibly executing a command in a new process

Constants
---------
DEVNULL: Special value that indicates that os.devnull should be used
PIPE:    Special value that indicates a pipe should be created
STDOUT:  Special value that indicates that stderr should go to stdout


Older API
=========
call(...): Runs a command, waits for it to complete, then returns
    the return code.
check_call(...): Same as call() but raises CalledProcessError()
    if return code is not 0
check_output(...): Same as check_call() but returns the contents of
    stdout instead of a return code
getoutput(...): Runs a command in the shell, waits for it to complete,
    then returns the output
getstatusoutput(...): Runs a command in the shell, waits for it to complete,
    then returns a (exitcode, output) tuple

2:基本操作方法

2.1:subprocess.call

    看下面的解釋:與os.system()功能是一樣;

print(help(subprocess.call))
"""
Help on function call in module subprocess:

call(*popenargs, timeout=None, **kwargs)
    Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.
    
    The arguments are the same as for the Popen constructor.  Example:
    
    retcode = call(["ls", "-l"])
"""
# encoding=gbk
import  subprocess

ret = subprocess.call(['ipconfig ','-a'])
print(ret)

ret = subprocess.call('ipconfig -a')
print(ret)

#
# print('*'*20)
# import os
# ret = os.system('ipconfig')

2.2:subprocess.check_call

與subprocess.call功能一樣,不過在命令退出狀態不爲0時,raise CalledProcessError(retcode, cmd)

print(help(subprocess.check_call))

"""
check_call(*popenargs, **kwargs)
    Run command with arguments.  Wait for command to complete.  If
    the exit code was zero then return, otherwise raise
    CalledProcessError.  The CalledProcessError object will have the
    return code in the returncode attribute.
    
    The arguments are the same as for the call function.  Example:
    
    check_call(["ls", "-l"])

"""

測試:在同級目錄下新建文件 test.py,內容如下:

import sys
print('in test')

sys.exit(1)
# encoding=gbk
import  subprocess


# print(help(subprocess.check_call))

try:
    # ret = subprocess.check_call('python test.py')
    ret = subprocess.check_call('python test.py')
    print(ret)
except subprocess.CalledProcessError as e:
    print('腳本異常退出',e.returncode,e.cmd)


"""
結果:
in test
腳本異常退出 1 python test.py

"""

2.3:subprocess.check_output

與subprocess.check_call一樣,在命令退出狀態不爲0時,raise CalledProcessError(retcode, cmd);不過其返回值是命令的輸出。

# encoding=gbk
import  subprocess

# print(help(subprocess.check_output))

try:
    # ret = subprocess.check_output('python test.py')
    ret = subprocess.check_output(['python','test.py'])
    print('ret=',ret)
except subprocess.CalledProcessError as e:
    print('腳本異常退出',e.returncode,e.cmd)

2.4:subprocess.getoutput

getoutput(cmd)    返回命令執行中的輸出結果,同os.popen返回的結果
    Return output (stdout or stderr) of executing cmd in a shell.

# encoding=gbk
import  subprocess

# print(help(subprocess.getoutput))

# ret = subprocess.getoutput('python test.py')
ret = subprocess.getoutput(['python','test.py'])
print('ret=',ret)

2.5:subprocess.getstatusoutput

getstatusoutput(cmd)  返回命令退出狀態,及命令執行中的輸出。
    Return (exitcode, output) of executing cmd in a shell.
 

# encoding=gbk
import  subprocess

print(help(subprocess.getstatusoutput))

# ret = subprocess.getstatusoutput('python test.py')
ret = subprocess.getstatusoutput(['python','test.py'])
print('ret=',ret)      # 輸出 ret= (2, 'in test')

2.6:subprocess.run

run(*popenargs, input=None, timeout=None, check=False, **kwargs),返回CompletedProcess

使用 print(help(subprocess.run)) 查看詳情說明。

參數 說明 描述
popenargs 可以是一個字符串,可以是一個包含程序參數的列表。 當爲字符串時,需要是程序的路徑纔可以,或者shell爲True
stdin、stdout 和 stderr: stdout爲None時不捕獲,命令的輸出 子進程的標準輸入、輸出和錯誤。其值可以是 subprocess.PIPE、
subprocess.DEVNULL、一個已經存在的文件描述符、已經打開的文件對象或者 None
check check=True時,狀態爲非0時拋出CalledProcessError 是否檢測命令的退出狀態
universal_newlines

universal_newlines=True時stdout 的輸出結果爲字符串,同時input也需要是字符串

universal_newlines=False時stdout 的輸出結果爲Bytes,同時input也需要是Bytes

 
encoding  encoding='gbk'
 encoding='utf-8'
 encoding是告訴python,命令的輸出結果是什麼編碼格式。stdin、stdout 和 stderr 可以接收字符串數據,並以該編碼方式解碼命令中輸出的結果(命令中的輸出結果是gbk,就使用gbk)。否則只接收 bytes 類型的數據
timeout    如果發生超時,子進程將被殺死並等待。 TimeoutExpired 異常將在子進程中斷後被拋出。

測試:
 在同目錄下新建文件test.py
其內容如下:

# encoding=gbk
import sys
print('in test 中國 1234')
print('int test,sys.argv=[',sys.argv,']')
sys.exit(2)
# encoding=gbk
import  subprocess
# print(help(subprocess.run))

# ret = subprocess.run('python test.py')
# 1:只有命令參數,只執行命令,返回值中 有已執行的命令,returncode
ret = subprocess.run(['python','test.py'])
print('ret_001=',ret)  # ret_001= CompletedProcess(args=['python', 'test.py'], returncode=2)

# 2:增加stdout參數,返回值中能捕獲命令的輸出結果,結果是bytes
ret = subprocess.run(['python','test.py'],stdout=subprocess.PIPE)
print('ret_002=',ret)  # ret_002= CompletedProcess(args=['python', 'test.py'], returncode=2, stdout=b"in test \xd6\xd0\xb9\xfa 1234\r\nint test,sys.argv=[ ['test.py'] ]\r\n")

# 3:在上面2基礎上增加universal_newlines=True,輸出結果是字符串
ret = subprocess.run(['python','test.py'],stdout=subprocess.PIPE,universal_newlines=True)
print('ret_003=',ret)  # ret_003= CompletedProcess(args=['python', 'test.py'], returncode=2, stdout="in test 中國 1234\nint test,sys.argv=[ ['test.py'] ]\n")


# 4: 添加 shell
# ret = subprocess.run(['dir'])   # FileNotFoundError
# print('ret_004-1=',ret)  #

ret = subprocess.run(['dir'],shell=True)
print('ret_004-2=',ret)  #



# 5:在上面3基礎上增加check=True,拋出 CalledProcessError異常,因爲在test.py中退出狀態碼爲2
ret = subprocess.run(['python','test.py'],stdout=subprocess.PIPE,universal_newlines=True,check=True)
print('ret_005=',ret)  #

2.7:subprocess.Popen

在一個新的進程中執行子程序。在 POSIX,此類使用類似於 os.execvp() 的行爲來執行子程序。在 Windows,此類使用了 Windows CreateProcess() 函數。subprocess模塊的底層的進程創建與管理由 Popen 類處理。它提供了很大的靈活性,因此開發者能夠處理未被上面函數覆蓋的不常見用例。上面那些函數都是調用subprocess.Popen來實現的。

其參數如下:

args, bufsize=-1, executable=None,
             stdin=None, stdout=None, stderr=None,
             preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
             shell=False, cwd=None, env=None, universal_newlines=False,
             startupinfo=None, creationflags=0,
             restore_signals=True, start_new_session=False,
             pass_fds=(), *, encoding=None, errors=None

bufsize參數:
如果指定了bufsize參數作用就和內建函數open()一樣:0表示不緩衝,1表示行緩衝,其他正數表示近似的緩衝區字節數,負數表
示使用系統默認值。默認是0。

executable參數:
指定要執行的程序。它很少會被用到:一般程序可以由args 參數指定。如果shell=True ,executable可以用於指定用哪個shell來執行(比如bash、csh、zsh等)。*nix下,默認是 /bin/sh ,windows下,就是環境變量 COMSPEC的值。windows下,只有當你要執行的命令確實是shell內建命令(比如dir ,copy 等)時,你才需要指定shell=True,而當你要執行一個基於命令行的批處理腳本的時候,不需要指定此項。

stdin stdout和stderr:
stdin stdout和stderr,分別表示子程序的標準輸入、標準輸出和標準錯誤。可選的值有PIPE或者一個有效的文件描述符(其實是個正整數)或者一個文件對象,還有None。如果是PIPE,則表示需要創建一個新的管道,如果是None,不會做任何重定向工作,子進程的文件描述符會繼承父進程的。另外,stderr的值還可以是STDOUT,表示子進程的標準錯誤也輸出到標準輸出。

preexec_fn參數:
如果把preexec_fn設置爲一個可調用的對象(比如函數),就會在子進程被執行前被調用。(僅限*nix)

close_fds參數:
如果把close_fds設置成True,*nix下會在開子進程前把除了0、1、2以外的文件描述符都先關閉。在 Windows下也不會繼承其他文件描述符。

shell參數:
如果把shell設置成True,指定的命令會在shell裏解釋執行。

cwd參數:
如果cwd不是None,則會把cwd做爲子程序的當前目錄。注意,並不會把該目錄做爲可執行文件的搜索目錄,所以不要把程序文件所在目錄設置爲cwd 。

env參數:
如果env不是None,則子程序的環境變量由env的值來設置,而不是默認那樣繼承父進程的環境變量。注意,即使你只在env裏定義了某一個環境變量的值,也會阻止子程序得到其他的父進程的環境變量(也就是說,如果env裏只有1項,那麼子進程的環境變量就只有1個了)。

universal_newlines參數:
如果把universal_newlines 設置成True,則子進程的stdout和stderr被視爲文本對象,並且不管是*nix的行結束符(’/n’),還是老mac格式的行結束符(’/r’ ),還是windows 格式的行結束符(’/r/n’ )都將被視爲 ‘/n’ 。

startupinfo和creationflags參數:
如果指定了startupinfo和creationflags,將會被傳遞給後面的CreateProcess()函數,用於指定子程序的各種其他屬性,比如主窗口樣式或者是子進程的優先級等。(僅限Windows)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章