[Python] subprocess module

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种类型,可以是字串或整数等

你可能感兴趣的:([Python] subprocess module)