11

I'm new to subprocessing.

I just need a really simple win32 example of communicate() between a parent.py and child.py. A string sent from parent.py to child.py, altered by child.py and sent back to parent.py for print() from parent.py.

I'm posting this because examples I have found end up either not being win32 or not using a child which just confuses me.

Thanks for you help.

Rhys
  • 4,926
  • 14
  • 41
  • 64

1 Answers1

21

Here is a simple example as per your requirements. This example is Python 3.x (slight modifications are required for 2.x).

parent.py

import subprocess
import sys

s = "test"
p = subprocess.Popen([sys.executable, "child.py"],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)
out, _ = p.communicate(s.encode())
print(out.decode())

child.py

s = input()
s = s.upper()
print(s)

I wrote and tested this on Mac OS X. There is no platform-specific code here, so there is no reason why it won't work on Win32 also.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • thanks for the quick response. It does not seem to be accepting raw_input. probably because I'm using python 3. I tried to change it to input but this raised another error 'EOFError: EOF when reading a line'. – Rhys Dec 28 '11 at 06:58
  • Ok, I'll modify the example for Python 3.x. – Greg Hewgill Dec 28 '11 at 07:00
  • i still seem to get ... self.stdin.write(input) ... TypeError: must be bytes or buffer, not str – Rhys Dec 28 '11 at 07:06
  • You will need `p.communicate(s.encode())` as I wrote above. This is because Python 3 strings are Unicode and must be encoded before writing to a pipe (and decoded after reading). – Greg Hewgill Dec 28 '11 at 07:07
  • ahh i see now. needed to refresh page. thanks a million. unfortunatly i cant give you that many reps but it looks like you have plenty :P – Rhys Dec 28 '11 at 07:09
  • hey I know this is a bit of an addition but ... if I wanted child.py to be a binary file I get 'SyntaxError: Non-UTF-8 code starting with ... but no encoding declared'. How can I change parent.py to deal with .exe files? – Rhys Dec 28 '11 at 07:28
  • oh I just removed 'sys.executable' and that seemed to do the trick – Rhys Dec 28 '11 at 07:30
  • Yup, `sys.executable` is the path to the current Python binary. – Greg Hewgill Dec 28 '11 at 07:34