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種類型,可以是字串或整數等