成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

python模塊之subprocess模塊級(jí)方法

gitmilk / 2593人閱讀

摘要:參數(shù)將作為子進(jìn)程的標(biāo)準(zhǔn)輸入傳遞給方法,必須是需要指定或參數(shù),或者設(shè)置為或類型。源碼模塊還提供了版本中模塊的相關(guān)函數(shù)。實(shí)際上是調(diào)用函數(shù),在中執(zhí)行類型的指令,返回形式的元組,包含和是使用解碼的字符串,并刪除了結(jié)尾的換行符。

subprocess.run()

運(yùn)行并等待args參數(shù)指定的指令完成,返回CompletedProcess實(shí)例。

參數(shù):(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)。除input, capture_output, timeout, check,其他參數(shù)與Popen構(gòu)造器參數(shù)一致。

capture_output:如果設(shè)置為True,表示重定向stdout和stderr到管道,且不能再傳遞stderrstdout參數(shù),否則拋出異常。

input:input參數(shù)將作為子進(jìn)程的標(biāo)準(zhǔn)輸入傳遞給Popen.communicate()方法,必須是string(需要指定encoding或errors參數(shù),或者設(shè)置text為True)或byte類型。非None的input參數(shù)不能和stdin參數(shù)一起使用,否則將拋出異常,構(gòu)造Popen實(shí)例的stdin參數(shù)將指定為subprocess.PIPE。

timeout:傳遞給Popen.communicate()方法。

check:如果設(shè)置為True,進(jìn)程執(zhí)行返回非0狀態(tài)碼將拋出CalledProcessError異常。

# 源碼

def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
    if input is not None:
        if "stdin" in kwargs:
            raise ValueError("stdin and input arguments may not both be used.")
        kwargs["stdin"] = PIPE
    
    if capture_output:
        if ("stdout" in kwargs) or ("stderr" in kwargs):
            raise ValueError("stdout and stderr arguments may not be used "
                             "with capture_output.")
        kwargs["stdout"] = PIPE
        kwargs["stderr"] = PIPE
    
    with Popen(*popenargs, **kwargs) as process:
        try:
            stdout, stderr = process.communicate(input, timeout=timeout)
        except TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise TimeoutExpired(process.args, timeout, output=stdout,
                                 stderr=stderr)
        except:  # Including KeyboardInterrupt, communicate handled that.
            process.kill()
            # We don"t call process.wait() as .__exit__ does that for us.
            raise
        retcode = process.poll()
        if check and retcode:
            raise CalledProcessError(retcode, process.args,
                                     output=stdout, stderr=stderr)
    return CompletedProcess(process.args, retcode, stdout, stderr)

python3.5版本前,call(), check_all(), checkoutput()三種方法構(gòu)成了subprocess模塊的高級(jí)API。

subprocess.call()

運(yùn)行并等待args參數(shù)指定的指令完成,返回執(zhí)行狀態(tài)碼(Popen實(shí)例的returncode屬性)。

參數(shù):(*popenargs, timeout=None, **kwargs)。與Popen構(gòu)造器參數(shù)基本相同,除timeout外的所有參數(shù)都將傳遞給Popen接口。

調(diào)用call()函數(shù)不要使用stdout=PIPEstderr=PIPE,因?yàn)槿绻舆M(jìn)程生成了足量的輸出到管道填滿OS管道緩沖區(qū),子進(jìn)程將因不能從管道讀取數(shù)據(jù)而導(dǎo)致阻塞。

# 源碼

def call(*popenargs, timeout=None, **kwargs):
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise
subprocess.check_call()

運(yùn)行并等待args參數(shù)指定的指令完成,返回0狀態(tài)碼或拋出CalledProcessError異常,該異常的cmdreturncode屬性可以查看執(zhí)行異常的指令和狀態(tài)碼。

參數(shù):(*popenargs, **kwargs)。全部參數(shù)傳遞給call()函數(shù)。

注意事項(xiàng)同call()

# 源碼

def check_call(*popenargs, **kwargs):
    retcode = call(*popenargs, **kwargs)
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd)
    return 0
subprocess.check_output()

運(yùn)行并等待args參數(shù)指定的指令完成,返回標(biāo)準(zhǔn)輸出(CompletedProcess實(shí)例的stdout屬性),類型默認(rèn)是byte字節(jié),字節(jié)編碼可能取決于執(zhí)行的指令,設(shè)置universal_newlines=True可以返回string類型的值。
如果執(zhí)行狀態(tài)碼非0,將拋出CalledProcessError異常。

參數(shù):(*popenargs, timeout=None, **kwargs)。全部參數(shù)傳遞給run()函數(shù),但不支持顯示地傳遞input=None繼承父進(jìn)程的標(biāo)準(zhǔn)輸入文件句柄。

要在返回值中捕獲標(biāo)準(zhǔn)錯(cuò)誤,設(shè)置stderr=subprocess.STDOUT;也可以將標(biāo)準(zhǔn)錯(cuò)誤重定向到管道stderr=subprocess.PIPE,通過CalledProcessError異常的stderr屬性訪問。

# 源碼

def check_output(*popenargs, timeout=None, **kwargs):
    if "stdout" in kwargs:
        raise ValueError("stdout argument not allowed, it will be overridden.")

    if "input" in kwargs and kwargs["input"] is None:
        # Explicitly passing input=None was previously equivalent to passing an
        # empty string. That is maintained here for backwards compatibility.
        kwargs["input"] = "" if kwargs.get("universal_newlines", False) else b""

    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
               **kwargs).stdout

subprocess模塊還提供了python2.x版本中commands模塊的相關(guān)函數(shù)。

subprocess.getstatusoutput(cmd)

實(shí)際上是調(diào)用check_output()函數(shù),在shell中執(zhí)行string類型的cmd指令,返回(exitcode, output)形式的元組,output(包含stderrstdout)是使用locale encoding解碼的字符串,并刪除了結(jié)尾的換行符。

# 源碼

try:
    data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT)
    exitcode = 0
except CalledProcessError as ex:
    data = ex.output
    exitcode = ex.returncode
if data[-1:] == "
":
    data = data[:-1]
return exitcode, data
subprocess.getoutput(cmd)

getstatusoutput()類似,但結(jié)果只返回output。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/43447.html

相關(guān)文章

  • python基礎(chǔ)教程:異步IO API

    摘要:具有以下基本同步原語子進(jìn)程提供了通過創(chuàng)建和管理子進(jìn)程的。雖然隊(duì)列不是線程安全的,但它們被設(shè)計(jì)為專門用于代碼。表示異步操作的最終結(jié)果。 Python的asyncio是使用 async/await 語法編寫并發(fā)代碼的標(biāo)準(zhǔn)庫(kù)。通過上一節(jié)的講解,我們了解了它不斷變化的發(fā)展歷史。到了Python最新穩(wěn)定版 3.7 這個(gè)版本,asyncio又做了比較大的調(diào)整,把這個(gè)庫(kù)的API分為了 高層級(jí)API和...

    vboy1010 評(píng)論0 收藏0
  • python模塊subprocess類與常量

    摘要:限于,可選的文件描述符序列,用于在父子進(jìn)程間保持開放。如果設(shè)置了,表示派生的進(jìn)程號(hào)子進(jìn)程返回碼,表示進(jìn)程未終止。如果未捕獲標(biāo)準(zhǔn)錯(cuò)誤返回方法如果非,拋出異常異常模塊的異?;愖舆M(jìn)程執(zhí)行超時(shí)。 常量 subprocess.DEVNULL:可傳遞給stdin, stdout, stderr參數(shù)的特殊值,意味著將使用特殊文件os.devnull重定向輸入輸出 subprocess.PIPE:可...

    Alan 評(píng)論0 收藏0
  • Python中的Subprocess模塊

    摘要:以前我一直用處理一些系統(tǒng)管理任務(wù)因?yàn)槲艺J(rèn)為那是運(yùn)行命令最簡(jiǎn)單的方式我們能從官方文檔里讀到應(yīng)該用模塊來運(yùn)行系統(tǒng)命令模塊允許我們創(chuàng)建子進(jìn)程連接他們的輸入輸出錯(cuò)誤管道,還有獲得返回值。模塊打算來替代幾個(gè)過時(shí)的模塊和函數(shù),比如命令。 以前我一直用os.system()處理一些系統(tǒng)管理任務(wù),因?yàn)槲艺J(rèn)為那是運(yùn)行l(wèi)inux命令最簡(jiǎn)單的方式.我們能從Python官方文檔里讀到應(yīng)該用subprocess...

    marek 評(píng)論0 收藏0
  • 寫了2年python,知道 if __name__ == '__main__'

    摘要:原因很簡(jiǎn)單,因?yàn)橹械拇淼木褪钱?dāng)前執(zhí)行的模塊名。缺點(diǎn)就是主程序會(huì)受待執(zhí)行程序的影響,會(huì)出現(xiàn)待執(zhí)行程序中拋異?;蛑鲃?dòng)退出會(huì)導(dǎo)致主程序也退出的尷尬問題。總結(jié)來說就是,一個(gè)是在子進(jìn)程中執(zhí)行代碼,一個(gè)是在當(dāng)前進(jìn)程中執(zhí)行代碼。 showImg(https://segmentfault.com/img/remote/1460000018607395?w=502&h=318); 相信剛接觸Pytho...

    wangbinke 評(píng)論0 收藏0
  • python執(zhí)行shell命令的方法

    摘要:執(zhí)行命令的方法模塊方式說明這個(gè)調(diào)用相當(dāng)直接,且是同步進(jìn)行的,程序需要阻塞并等待返回。返回值是依賴于系統(tǒng)的,直接返回系統(tǒng)的調(diào)用返回值,所以和是不一樣的。并能夠獲得新建進(jìn)程運(yùn)行的返回狀態(tài)。使用模塊的目的是替代等舊的函數(shù)或模塊。 python執(zhí)行shell命令的方法 os模塊 os.system方式: import os os.system(top) os.system(cat /proc...

    PumpkinDylan 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<