python subprocess.call() doesn't work with multiline shell commands

Question:

I would like to run this multiline shell commands:

echo 'a=?'
read a
echo "a=$a"

from a python script, using the subprocess.call() method.

I wrote this, in test.py file:

import shlex, subprocess

args = ["echo", 'a=?',"read", "a", "echo", "a=$a"]
subprocess.call(args)

and when I execute it, I have in terminal this report:

Armonicus@MyMacs-iMac MyNewFolder % python test.py
a=? read a echo a=$a

which is not at least close to what I expect.
Can I have some support from anyone, please?

Asked By: FelixTheCat

||

Answers:

There are a couple of issues with your approach here.

First, if what you’re trying to do is prompt the user for input from the command line, then you can use Python builtins instead of a subprocess:

a = input('a=?')
print(a)

If you do want to call a subprocess with multiple commands, you need to either make separate calls for each command, or invoke a shell and execute the commands within it. For example:

subprocess.call("echo 'a=?'; read a; echo $a", shell=True)
Answered By: Jeff
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.