python3 subprogress 模塊的使用 代替shell編寫腳本

subprogress允許我們創(chuàng)建新進(jìn)程,進(jìn)程之間通過stdin,stdout,stderr管道進(jìn)行通信,該模塊自從python2.4版本引入

這個(gè)模塊是為了替代 os.system os.spawn*這兩個(gè)模塊產(chǎn)生的。也就是說,可以代替shell編寫命令行腳本。

run 方法

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.
推薦使用run方法處理大部分場景,如果有更高級的需求,可以使用底層的Popen接口。
run()方法是python3.5加入的。(怪不得網(wǎng)上的教程都沒看到這個(gè)方法)

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)

不過這個(gè)模塊貌似只適合linux下使用。因?yàn)椴恢С謕owershell的那些命令(cmd 還是支持的)。windows下只有exe的可執(zhí)行命令行程序比較適合調(diào)用吧。還有一點(diǎn)是,命令執(zhí)行結(jié)果返回0和1,這點(diǎn)就和linux的命令式一致的。

run方法包含了大部分最常用的參數(shù),而且很多接口參數(shù)都是和Popen一致

class subprocess.CompletedProcess
subprocess.CompletedProcess 是run方法的返回值
包含以下參數(shù):

The return value from run(), representing a process that has finished.

args
The arguments used to launch the process. This may be a list or a string.

returncode
Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.

A negative value -N indicates that the child was terminated by signal N (POSIX only).

stdout
Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stdout was not captured.

If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.

stderr
Captured stderr from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stderr was not captured.

check_returncode()
If returncode is non-zero, raise a CalledProcessError.

# win10 1809  python3.7
import subprocess

res = subprocess.run(['ffmpeg','-h'])
# subprocess.CompletedProcess
print('args: ',res.args)
print('stdout: ',res.stdout)
print('stderr: ',res.stderr)
# 當(dāng)returncode為非零值,拋出錯(cuò)誤  CalledProcessError
res.check_returncode()
args:  ['ffmpeg', '-h']
stdout:  None
stderr:  None

subprocess.DEVNULL 應(yīng)該就是linux里的 /dev/null
subprocess.PIPE 可以提供給stdin,stdout or stderr 參數(shù)

exception subprocess.SubprocessError
exception subprocess.TimeoutExpired
。。。

最常用的參數(shù)
args 調(diào)用的命令,可以是字符串,或者一系列的參數(shù)比如列表。
stdin stdout,stderr 程序的標(biāo)準(zhǔn)輸入。。。 有效的參數(shù)值是PIPE和DEVNULL

text ,開啟文本模式,可以用encoding指定編碼,stdin等都會(huì)用文本形式傳遞。如果不開啟,他們會(huì)以二進(jìn)制流形式傳遞
在python3.7 text參數(shù)更名為universal_newlines

shell ,如果shell設(shè)置為true,命令會(huì)通過真正的shell環(huán)境執(zhí)行。

# win10 1809  python3.7
import subprocess

subprocess.run('dir', shell=True)
CompletedProcess(args='dir', returncode=0)

popen對象

底層的進(jìn)程創(chuàng)建和管理使用Popen class,靈活性比較高。

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

Popen.send_signal(signal)

Popen.terminate() 停止
Popen.kill() 殺死子進(jìn)程
Popen.pid 子進(jìn)程的進(jìn)程號
Popen.returncode 此進(jìn)程的退出碼

Popen.poll() 檢查子進(jìn)程是否停止

Popen.wait(timeout=None) 等待子進(jìn)程停止,如果子進(jìn)程超時(shí)還不termiate,會(huì)TimeoutExpired 異常

Popen.communicate(input=None, timeout=None)與進(jìn)程交互,發(fā)送數(shù)據(jù)到stdin,并讀取stdout和stderr直到eof
會(huì)返回一個(gè)元組(stdout_data, stderr_data),

Popen.stdin
如果 stdin 參數(shù)為 PIPE,此屬性是一個(gè)類似 open() 返回的可寫的流對象。如果 encoding 或 errors 參數(shù)被指定或者 universal_newlines 參數(shù)為 True,則此流是一個(gè)文本流,否則是字節(jié)流。如果 stdin 參數(shù)非 PIPE, 此屬性為 None。

Popen.stdout
如果 stdout 參數(shù)是 PIPE,此屬性是一個(gè)類似 open() 返回的可讀流。從流中讀取子進(jìn)程提供的輸出。如果 encoding 或 errors 參數(shù)被指定或者 universal_newlines 參數(shù)為 True,此流為文本流,否則為字節(jié)流。如果 stdout 參數(shù)非 PIPE,此屬性為 None。
Popen.stderr
如果 stderr 參數(shù)是 PIPE,此屬性是一個(gè)類似 open() 返回的可讀流。從流中讀取子進(jìn)程提供的輸出。如果 encoding 或 errors 參數(shù)被指定或者 universal_newlines 參數(shù)為 True,此流為文本流,否則為字節(jié)流。如果 stderr 參數(shù)非 PIPE,此屬性為 None。

原來python官方文檔中文也更新了不少

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、介紹 subprocess模塊可以生成新的進(jìn)程,連接到它們的input/output/error管道,同時(shí)獲取...
    rr1990閱讀 68,578評論 2 18
  • 處于學(xué)習(xí)別人代碼風(fēng)格階段,github參考學(xué)習(xí)程序程序開頭會(huì)有 一是用來指定腳本語言為 Python,二是用來指定...
    lifesmily閱讀 1,326評論 0 0
  • From: https://blog.linuxeye.com/375.html 從Python 2.4開始,Py...
    pzka158閱讀 3,116評論 0 2
  • 概述 python中一般推薦的執(zhí)行shell命令行的方式有兩種,os.popen與subprocess.Popen...
    sanerersan閱讀 4,031評論 0 0
  • 網(wǎng)絡(luò)編程 一.楔子 你現(xiàn)在已經(jīng)學(xué)會(huì)了寫python代碼,假如你寫了兩個(gè)python文件a.py和b.py,分別去運(yùn)...
    go以恒閱讀 2,249評論 0 6

友情鏈接更多精彩內(nèi)容