R
R
Renat Iliev2016-05-01 19:04:33
Python
Renat Iliev, 2016-05-01 19:04:33

How to organize communication of processes through stdin/stdout?

My task is somewhat non-trivial, to organize communication between processes without sockets (only stdin / stdout).
The main script that runs the adjacent script:

import subprocess
messages = ['test1', 'test2', 'test3', 'test4', 'test5', ]
process = subprocess.Popen(['C:\\Python27\\python.exe', 'subscript.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
while len(messages)>0:
  process.stdin.write(messages.pop() + '\n')
  print process.stdout.readline()

Next to it lies subscript.py :
import sys
while True:
  print sys.stdin.readline()

After running the first file, nothing happens. As I understand it, the data is sent to the stdin of the child process, but the child process itself cannot read them (or do they not reach it?).
If you open subprocess.py with your hands , it works as it should.
What could be the problem?
UPD:
If in the first file after process.stdin.write(.....) add process.stdin.close() , then one value is sent, but stdin is closed for writing...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Renat Iliev, 2016-05-01
@IzeBerg

Found a solution:

import subprocess
messages = ['test1', 'test2', 'test3', 'test4', 'test5', ]
process = subprocess.Popen(['C:\\Python27\\python.exe', 'subscript.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
while len(messages)>0:
  process.stdin.write(messages.pop() + '\n')
  process.stdin.flush() 
  print process.stdout.readline()
process.terminate()

subscript.py :
import sys
while True:
  sys.stdout.write(sys.stdin.readline())
  sys.stdout.flush()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question