Python 調用 shell 命令的模組總結

來源:互聯網
上載者:User

標籤:

os.system(‘cat /proc/cpuinfo‘)

    阻塞,返回shell執行參數命令的狀態,即成功返回0

os.popen(‘cat /proc/cpuinfo‘)

    阻塞,返回file read的對象,對該對象進行 read() 可以擷取shell執行參數命令的結果,即標準輸出

commands.getstatus(‘/proc/cputinfo‘)

    阻塞,返回參數指定的系統檔案的詳細屬性

commands.getoutput(‘cat /proc/cpuinfo‘)

    阻塞,返回shell執行參數命令的結果

commands.getstatusoutput(‘cat /proc/cpuinfo‘)

    阻塞,返回shell狀態和shell輸出的元組(status, output)

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

    阻塞,返回shell狀態,禁用 PIPE 參數

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

    阻塞,shell 執行成功返回0, 否則無返回,並拋出包含shell錯誤狀態的 CalledProcessError 異常,禁用PIPE參數

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

    阻塞,shell 執行成功返回shell結果,否則無返回,並拋出包含shell錯誤狀態的 CalledProcessError 異常,禁用PIPE參數

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)

    不阻塞,返回Popen對象

    subprocess 參數:

        args:字串或列表(*nix 下第一項視為命令,後面是命令參數)

        bufsize:預設 0 不緩衝,1 行緩衝,其他正數表示緩衝大小,負數表示使用系統預設全緩衝

        stdin stdout stderr:subprocess.PIPE 表示管道操作,subprocess.STDOUT 表示輸出到標準輸出

        preexec_fn:*nix 下子進程被執行前調用

        shell:True 時表示指定命令在shell裡解釋執行

        subprocess.PIPE:用於stdin、stdout 和 stderr ,表示建立並寫入一個管道

        subprocess.STDOUT:用於 stderr,表示標準錯誤重新導向到標準輸出

    Popen 對象屬性:

        Popen.poll()    檢查子進程是否結束,0 表示退出

        Popen.wait()    等待子進程結束,注意子進程是否寫管道

        Popen.communicate(input=None)    與子進程互動,字串資料發送到stdin,並從stdout和stderr讀資料,知道EOF,等待子進程結束。注意讀寫stdin、stdout或stderr時要給定PIPE參數。返回元組(stdoutdata, stderrdata)。

        Popen.send_signal(signal)    給子進程發送訊號

        Popen.terminate()    停止子進程

        Popen.kill()    殺死子進程

        Popen.stdin Popen.stdout Popen.stderr    PIPE參數時為檔案對象,否則None

        Popen.pid    子進程的進程號

        Popen.returncode    None表示子進程沒終止,負數-N表示子進程被N號訊號終止

        




Python 調用 shell 命令的模組總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.