2013-03-16 80 views
7

我想知道是否subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",shell=True)将在不同的服务器上被shzsh而不是bash解释?子进程中`shell = True`中的`shell`是否意味着`bash`?

任何人都有这个想法?

我该怎么做才能确保它被bash解释?

+0

这意味着 - 使用默认的外壳 - 不管它默认是 – 2013-03-16 12:46:48

+0

@JonClements谢谢,乔恩!但是我应该怎么做才能确保它被bash解释? – 2013-03-16 12:47:24

+1

@Firegun调用'/ usr/bin/env bash'并为其输入命令。 – millimoose 2013-03-16 12:47:53

回答

22

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参数来替换默认:

...如果壳=真,在 Unix的可执行文件参数指定为 缺省更换外壳/ bin/sh的。

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

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

3

要指定外壳,use the executable parametershell=True

如果壳=真,在Unix上执行的参数指定默认的/ bin/sh的一个 更换外壳。

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

显然,使用可执行参数是清洁的,但它也可以从SH致电击:

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