Bash命令可以在外壳中运行,但不能通过python suprocess.run运行

时间:2019-06-24 21:01:44

标签: python bash

如果我在ubuntu shell中运行此命令:

debconf-set-selections <<< 'postfix postfix/mailname string server.exmaple.com'

它成功运行,但是如果我通过python运行它:

>>> from subprocess import run
>>> run("debconf-set-selections <<< 'postfix postfix/mailname string server.exmaple.com'", shell=True)
/bin/sh: 1: Syntax error: redirection unexpected
CompletedProcess(args="debconf-set-selections <<< 'postfix postfix/mailname string server.exmaple.com'", returncode=2)

我不明白为什么python试图解释是否存在重定向等。如何使命令成功运行,以便可以对应用程序的安装进行脚本编写,例如后缀在这种情况下是通过python(不是普通的bash脚本)?

我尝试了各种形式的双引号和单引号(如其他文章所推荐),但没有成功。

1 个答案:

答案 0 :(得分:1)

subprocess使用/bin/sh作为外壳程序,并且您的系统可能不支持此处字符串(<<<),因此会出错。

subprocess来源:

if shell:
    # On Android the default shell is at '/system/bin/sh'.
    unix_shell = ('/system/bin/sh' if
                  hasattr(sys, 'getandroidapilevel') else '/bin/sh')

您可以将命令作为支持此字符串的任何shell的参数运行,例如bash

run('bash -c "debconf-set-selections <<< \"postfix postfix/mailname string server.exmaple.com\""', shell=True)

请小心报价。

或者更好的是,您可以保留POSIX并使用echo和管道通过STDIN进行传递:

run("echo 'postfix postfix/mailname string server.exmaple.com' | debconf-set-selections", shell=True)