run_the_race
run_the_race

Reputation: 2418

Bash command can run in the shell, but not via python suprocess.run

If I run this command in ubuntu shell:

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

It runs successfully, but if I run it via 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)

I don't understand why python is trying to interpret whether there is redirection etc. How does one make the command successfully run so one can script installation of an application, e.g. postfix in this case via python (not a normal bash script)?

I have tried various forms with double and single quotes (as recommended in other posts), with no success.

Upvotes: 1

Views: 106

Answers (1)

heemayl
heemayl

Reputation: 42087

subprocess uses /bin/sh as shell, and presumably your system's one does not support here-string (<<<), hence the error.

From subprocess source:

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

You can run the command as an argument to any shell that supports here string e.g. bash:

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

Be careful with the quoting.

Or better you can stay POSIX and use echo and pipe to pass via STDIN:

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

Upvotes: 1

Related Questions