2013-03-16 81 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 
相關問題