If there will only be one sub-process at a time, and the parent will wait for the child to finish, you can just use Popen.communicate()
. Example:
# Create child with a pipe to STDIN.
child = subprocess.Popen(..., stdin=subprocess.PIPE)
# Send JSON to child's STDIN.
# - WARNING: This will block the parent from doing anything else until the
# child process finishes
child.communicate(json_str)
Then, in the sub-process (if it is python), you can read it with:
# Read JSON from STDIN.
json_str = sys.stdin.read()
Or, if you'd like a more complicated use where the parent can write multiple times to multiple sub-processes, then in the parent process:
# Create child with a pipe to STDIN.
child = subprocess.Popen(..., stdin=subprocess.PIPE)
# Serialize and send JSON as a single line (the default is no indentation).
json.dump(data, child.stdin)
child.stdin.write('\n')
# If you will not write any more to the child.
child.stdin.close()
Then, in the child you would read each line when desired:
# Read a line, process it, and do it again.
for json_line in sys.stdin:
data = json.loads(json_line)
# Handle received data.