1

I have created a Subprocess object. The subprocess invokes a shell, I need to send the shell command provided below to it. The code I've tried:

from subprocess import Popen, PIPE

p = Popen(["code.exe","25"],stdin=PIPE,stdout=PIPE,stderr=PIPE)
print p.communicate(input='ping 8.8.8.8')

The command doesn't execute, nothing is being input into the shell. Thanks in advance.

Milan Velebit
  • 1,933
  • 2
  • 15
  • 32
Ruse Bolton
  • 11
  • 1
  • 3

1 Answers1

1

If I simulate code.exe to read the arg and then process stdin:

#!/usr/bin/env bash
echo "arg: $1"
echo "stdin:"
while read LINE
do
  echo "$LINE"
done < /dev/stdin

and slightly update your code:

import os
from subprocess import Popen, PIPE

cwd = os.getcwd()
exe = os.path.join(cwd, 'foo.sh')
p = Popen([exe, '25'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = p.communicate(input='aaa\nbbb\n')
for line in out.split('\n'):
    print(line)

Then the spawned process outputs:

arg: 25
stdin:
aaa
bbb

If input is changed without a \n though:

out, err = p.communicate(input='aaa')

Then it doesn't appear:

arg: 25
stdin:

Process finished with exit code 0

So you might want to look closely at the protocol between both ends of the pipe. For example this might be enough:

input='ping 8.8.8.8\n'

Hope that helps.

mjr104
  • 193
  • 1
  • 4
  • Why does my subprocess die after I communicate with it once? In the second time it say: you're writing to a closed file. – Alex Deft Jun 24 '19 at 19:34
  • 1
    If you submit a question showing your code it will be easier to answer. Ideally, you have logging in your child process to explain why it terminates. – mjr104 Jun 26 '19 at 05:29