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.

6
  • Have you checked the stderr of your process? Commented Nov 3, 2017 at 11:02
  • Yes it is empty at all.I think Commented Nov 3, 2017 at 11:03
  • So your code.exe spawns a shell? Commented Nov 3, 2017 at 11:08
  • Yes, it spawns the shell Commented Nov 3, 2017 at 11:13
  • Wait, why are you printing the p.communicate function? Commented Nov 3, 2017 at 11:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why does my subprocess die after I communicate with it once? In the second time it say: you're writing to a closed file.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.