我想知道subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",shell=True)
是否会在不同的服务器中由sh
或zsh
而不是bash
解释?
任何人都有这方面的想法?
我应该怎样做以确保它由bash
解释?
答案 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:
调用bashIn [27]: subprocess.call('''bash -c "if [ ! -d '{output}' ]; then mkdir -p {output}; fi"''', shell=True)
Out[27]: 0