Python下的subprocess模組的入門指引

來源:互聯網
上載者:User
在熟悉了Qt的QProcess以後,再回頭來看python的subprocess總算不覺得像以前那麼恐怖了。

和QProcess一樣,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)

這堆東西真讓人抓狂:

subprocess.Popen(["gedit","abc.txt"])subprocess.Popen("gedit abc.txt")

這兩個之中,後者將不會工作。因為如果是一個字串的話,必須是程式的路徑才可以。(考慮unix的api函數 exec,接受的是字串列表)

但是下面的可以工作

subprocess.Popen("gedit abc.txt", shell=True)

這是因為它相當於

subprocess.Popen(["/bin/sh", "-c", "gedit abc.txt"])

都成了sh的參數,就無所謂了

在Windows下,下面的卻又是可以工作的

subprocess.Popen(["notepad.exe", "abc.txt"])subprocess.Popen("notepad.exe abc.txt")

這是由於windows下的api函數CreateProcess接受的是一個字串。即使是列表形式的參數,也需要先合并成字串再傳遞給api函數。

類似上面

subprocess.Popen("notepad.exe abc.txt" shell=True)

等價於

subprocess.Popen("cmd.exe /C "+"notepad.exe abc.txt" shell=True)subprocess.call*

模組還提供了幾個便利函數(這本身也算是很好的Popen的使用例子了)

call() 執行程式,並等待它完成

def call(*popenargs, **kwargs):  return Popen(*popenargs, **kwargs).wait()

check_call() 調用前面的call,如果傳回值非零,則拋出異常

def check_call(*popenargs, **kwargs):  retcode = call(*popenargs, **kwargs)  if retcode:    cmd = kwargs.get("args")    raise CalledProcessError(retcode, cmd)  return 0

check_output() 執行程式,並返回其標準輸出

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對象

該對象提供有不少方法函數可用。而且前面已經用到了wait()/poll()/communicate()

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.