子进程中`shell = True`中的`shell`是否意味着`bash`?

时间:2013-03-16 12:45:40

标签: python shell subprocess

我想知道subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",shell=True)是否会在不同的服务器中由shzsh而不是bash解释?

任何人都有这方面的想法?

我应该怎样做以确保它由bash解释?

3 个答案:

答案 0 :(得分:25)

http://docs.python.org/2/library/subprocess.html

On Unix with shell=True, the shell defaults to /bin/sh

请注意,/ bin / sh通常符号链接到不同的内容,例如:在ubuntu:

$ ls -la /bin/sh
lrwxrwxrwx 1 root root 4 Mar 29  2012 /bin/sh -> dash

您可以使用executable参数替换默认值:

  

...如果shell = True,则打开   Unix可执行参数指定了替换shell   default / bin / sh。

subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",
                shell=True,
                executable="/bin/bash")

答案 1 :(得分:3)

您可以显式调用您选择的shell,但对于您发布的示例代码,这不是最佳方法。相反,只需直接在Python中编写代码即可。见这里:mkdir -p functionality in Python

答案 2 :(得分:3)

使用shell=True指定shell use the executable parameter

  

如果shell = True,则在Unix上,可执行参数指定a   替换shell为默认/ bin / sh。

In [26]: subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi", shell=True, executable='/bin/bash')
Out[26]: 0

显然,使用可执行参数更干净,但也可以从sh:

调用bash
In [27]: subprocess.call('''bash -c "if [ ! -d '{output}' ]; then mkdir -p {output}; fi"''', shell=True)
Out[27]: 0