Python下的subprocess模塊的入門(mén)指引
在熟悉了Qt的QProcess以后,再回頭來(lái)看python的subprocess總算不覺(jué)得像以前那么恐怖了。
和QProcess一樣,subprocess的目標(biāo)是啟動(dòng)一個(gè)新的進(jìn)程并與之進(jìn)行通訊。
subprocess.Popen
這個(gè)模塊主要就提供一個(gè)類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)
這堆東西真讓人抓狂:

subprocess.Popen(["gedit","abc.txt"])
subprocess.Popen("gedit abc.txt")
這兩個(gè)之中,后者將不會(huì)工作。因?yàn)槿绻且粋€(gè)字符串的話,必須是程序的路徑才可以。(考慮unix的api函數(shù) exec,接受的是字符串列表)
但是下面的可以工作
subprocess.Popen("gedit abc.txt", shell=True)
這是因?yàn)樗喈?dāng)于
subprocess.Popen(["/bin/sh", "-c", "gedit abc.txt"])
都成了sh的參數(shù),就無(wú)所謂了
在Windows下,下面的卻又是可以工作的
subprocess.Popen(["notepad.exe", "abc.txt"])
subprocess.Popen("notepad.exe abc.txt")
這是由于windows下的api函數(shù)CreateProcess接受的是一個(gè)字符串。即使是列表形式的參數(shù),也需要先合并成字符串再傳遞給api函數(shù)。
類似上面
subprocess.Popen("notepad.exe abc.txt" shell=True)
等價(jià)于
subprocess.Popen("cmd.exe /C "+"notepad.exe abc.txt" shell=True)
subprocess.call*
模塊還提供了幾個(gè)便利函數(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 output
Popen對(duì)象
該對(duì)象提供有不少方法函數(shù)可用。而且前面已經(jīng)用到了wait()/poll()/communicate()

相關(guān)文章
Python基于list的append和pop方法實(shí)現(xiàn)堆棧與隊(duì)列功能示例
這篇文章主要介紹了Python基于list的append和pop方法實(shí)現(xiàn)堆棧與隊(duì)列功能,結(jié)合實(shí)例形式分析了Python使用list定義及使用隊(duì)列的相關(guān)操作技巧,需要的朋友可以參考下2017-07-07
python統(tǒng)計(jì)字符串中指定字符出現(xiàn)次數(shù)的方法
這篇文章主要介紹了python統(tǒng)計(jì)字符串中指定字符出現(xiàn)次數(shù)的方法,涉及Python中count函數(shù)的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
Python Django使用forms來(lái)實(shí)現(xiàn)評(píng)論功能
這篇文章主要為大家詳細(xì)介紹了Python Django使用forms來(lái)實(shí)現(xiàn)評(píng)論功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
Python3.10動(dòng)態(tài)修改Windows系統(tǒng)本地IP地址
這篇文章主要介紹了Python3.10動(dòng)態(tài)修改Windows系統(tǒng)本地IP地址,需要的朋友可以參考下2023-05-05
Python算法中的時(shí)間復(fù)雜度問(wèn)題
時(shí)間復(fù)雜度用于度量算法的計(jì)算工作量,空間復(fù)雜度用于度量算法占用的內(nèi)存空間。這篇文章主要介紹了Python算法中的時(shí)間復(fù)雜度,需要的朋友可以參考下2019-11-11
Python openpyxl 無(wú)法保存文件的解決方案
這篇文章主要介紹了Python openpyxl 無(wú)法保存文件的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03

