[Python] subprocess module

來源:互聯網
上載者:User

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

在內部呼叫下面的函數,所有參數原封不動傳過去

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可以是python序列(sequence)或一個簡單字串

一般情況下推薦用序列的方式,因為可以處理各種引號空格escaping arguments等等

Providing a sequence of arguments is generallypreferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

但如果指定shell=True,就必須用字串方式,所有的參數都必須包含在單個字串裡,比如"ls dirName",否則python會執行成 /bin/sh -c ls dirName。也就是dirName變成了傳給/bin/sh的參數,而沒有給ls。

If shell is True, it isrecommended to pass args as a string rather than as a sequence.

If args is a sequence, the first item specifies the command string, andany additional items will be treated as additional arguments to the shellitself. That is to say,Popen
does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

如果要執行的命令有一長串很複雜的參數,要分解成單個的sequence element會很麻煩。可以用shlex.split()來完成

用序列方式時,單個element不能有空格。["ls", "-l"]可以,["ls ", "-l"]錯!

註:這兩天才發現上面sequence的概念理解有誤。python中sequence有7種類型,可以是字串或整數等

聯繫我們

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