Does the `shell` in `shell=True` in subprocess mea

2020-03-12 07:01发布

I was wondering whether subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",shell=True) will be interpreted by sh orzsh instead of bash in different server?

Anyone has ideas about this?

What should I do to make sure that it's interpreted by bash?

3条回答
forever°为你锁心
2楼-- · 2020-03-12 07:24

To specify the shell, use the executable parameter with shell=True:

If shell=True, on Unix the executable argument specifies a replacement shell for the default /bin/sh.

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

Clearly, using the executable parameter is cleaner, but it is also possible to call bash from sh:

In [27]: subprocess.call('''bash -c "if [ ! -d '{output}' ]; then mkdir -p {output}; fi"''', shell=True)
Out[27]: 0
查看更多
劳资没心,怎么记你
3楼-- · 2020-03-12 07:27

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

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

Note that /bin/sh is often symlinked to something different, e.g. on ubuntu:

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

You can use the executable argument to replace the default:

... If shell=True, on Unix the executable argument specifies a replacement shell for the default /bin/sh.

subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",
                shell=True,
                executable="/bin/bash")
查看更多
狗以群分
4楼-- · 2020-03-12 07:36

You can explicitly invoke the shell of your choice, but for the example code you posted this is not the best approach. Instead, just write the code in Python directly. See here: mkdir -p functionality in Python

查看更多
登录 后发表回答