Solution for Passing multiple lines to a program within a python script
is Given Below:
I have to run a program in several folders and thus want to do this in a python script instead of manually having to execute it from a terminal. The program takes a multiline arguments and is called from the terminal by:
cad arguments1 <<EOF
> arguments2
> arguments3
> END
> EOF
I tried to do this with
subprocess.Popen(["cad arguments1 <<EOFn","arguments2n","arguments3n","ENDn","EOF], shell = True)
and different variants thereof like putting all arguments into a string and running
subprocess.Popen(["cad", string], shell = True)
Tried without newline, running each line as a new subprocess.Popen etc. The program is called correctly but the arguments on the new lines (arguments2, arguments3, END and EOF are not send to the program correctly and hence the program fails.
When you use shell=True
, you have to provide the command as a single string, not a list.
subprocess.Popen("""cad arguments1 <<EOF
arguments2
arguments3
END
EOF""", shell = True)
But rather than using a here-doc, you can pipe the input to the process from Python.
proc = subprocess.Popen(["cad", "arguments1"], stdin=subprocess.PIPE, text=True)
proc.communicate("""arguments2
arguments3
END""")