【问题标题】:Does the `shell` in `shell=True` in subprocess means `bash`?子进程中的`shell = True`中的`shell`是否意味着`bash`?
【发布时间】:2013-03-05 04:08:11
【问题描述】:

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

有人对此有想法吗?

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

【问题讨论】:

  • 这意味着 - 使用默认外壳 - 无论默认是什么
  • @JonClements 谢谢,乔恩!但是我应该怎么做才能确保它被 bash 解释?
  • @Firegun 调用 /usr/bin/env bash 并将您的命令作为输入提供给它。

标签: python shell subprocess


【解决方案1】:

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 的可执行参数为 默认/bin/sh。

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

【讨论】:

    【解决方案2】:

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

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

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

    显然,使用executable参数更简洁,但也可以从sh调用bash:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-05
        • 2013-08-30
        • 2011-03-11
        • 1970-01-01
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多