python学习之subprocess模块
subprocess.Popen
這個模塊主要就提供一個類Popen:
class subprocess.Popen( 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 | 字符串或者列表 |
| bufsize | 0 無緩沖 |
| executable | 一般不用吧,args字符串或列表第一項表示程序名 |
| stdin | None 沒有任何重定向,繼承父進(jìn)程 |
| preexec_fn | 鉤子函數(shù), 在fork和exec之間執(zhí)行。(unix) |
| close_fds | unix 下執(zhí)行新進(jìn)程前是否關(guān)閉0/1/2之外的文件 |
| shell | 為真的話 |
| cwd | 設(shè)置工作目錄 |
| env | 設(shè)置環(huán)境變量 |
| universal_newlines | 各種換行符統(tǒng)一處理成 '\n' |
| startupinfo | window下傳遞給CreateProcess的結(jié)構(gòu)體 |
| creationflags | windows下,傳遞CREATE_NEW_CONSOLE創(chuàng)建自己的控制臺窗口 |
- 當(dāng)初最感到困擾的就是 args 參數(shù)。可以是一個字符串,可以是一個列表。
?
subprocess.Popen(["gedit","abc.txt"]) subprocess.Popen("gedit abc.txt")這兩個之中,后者將不會工作。因為如果是一個字符串的話,必須是程序的路徑才可以。(考慮unix的api函數(shù) exec,接受的是字符串列表)
- 但是下面的可以工作
?
subprocess.Popen("gedit abc.txt", shell=True)這是因為它相當(dāng)于
subprocess.Popen(["/bin/sh", "-c", "gedit abc.txt"])都成了sh的參數(shù),就無所謂了
- 在Windows下,下面的卻又是可以工作的
?
subprocess.Popen(["notepad.exe", "abc.txt"]) subprocess.Popen("notepad.exe abc.txt")這是由于windows下的api函數(shù)CreateProcess接受的是一個字符串。即使是列表形式的參數(shù),也需要先合并成字符串再傳遞給api函數(shù)。
- 類似上面
?
subprocess.Popen("notepad.exe abc.txt" shell=True)等價于
subprocess.Popen("cmd.exe /C "+"notepad.exe abc.txt" shell=True)subprocess.call*
模塊還提供了幾個便利函數(shù)(這本身也算是很好的Popen的使用例子了)
- call() 執(zhí)行程序,并等待它完成
?
def call(*popenargs, **kwargs): return Popen(*popenargs, **kwargs).wait()- check_call() 調(diào)用前面的call,如果返回值非零,則拋出異常
?
def check_call(*popenargs, **kwargs): retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") raise CalledProcessError(retcode, cmd) return 0- check_output() 執(zhí)行程序,并返回其標(biāo)準(zhǔn)輸出
?
def check_output(*popenargs, **kwargs): process = Popen(*popenargs, stdout=PIPE, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") raise CalledProcessError(retcode, cmd, output=output) return outputPopen對象
該對象提供有不少方法函數(shù)可用。而且前面已經(jīng)用到了wait()/poll()/communicate()
| poll() | 檢查是否結(jié)束,設(shè)置返回值 |
| wait() | 等待結(jié)束,設(shè)置返回值 |
| communicate() | 參數(shù)是標(biāo)準(zhǔn)輸入,返回標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)出錯 |
| send_signal() | 發(fā)送信號 (主要在unix下有用) |
| terminate() | 終止進(jìn)程,unix對應(yīng)的SIGTERM信號,windows下調(diào)用api函數(shù)TerminateProcess() |
| kill() | 殺死進(jìn)程(unix對應(yīng)SIGKILL信號),windows下同上 |
| stdin | 參數(shù)中指定PIPE時,有用 |
| pid | 進(jìn)程id |
| returncode | 進(jìn)程返回值 |
參考
轉(zhuǎn)載于:https://www.cnblogs.com/zmlctt/p/4226584.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的python学习之subprocess模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 农业银行定期存款利率表2021大额存单,
- 下一篇: [python]使用virtualenv