Roman Dmitrienko
Roman Dmitrienko

Reputation: 4235

Communication between a Python parent and C child processes in Linux

I am developing a Python application that needs to spawn a child process (written in C) from time to time, to feed it some binary data and to get a reply. The child process will only be spawned when needed and will only serve one request. What are my options here? Is it safe to use stdin/stdout?

Upvotes: 2

Views: 798

Answers (1)

ilent2
ilent2

Reputation: 5241

from subprocess import Popen,PIPE

# Example with output only
p = Popen(["echo", "This is a test"], stdout=PIPE)
out, err = p.communicate()
print out.rstrip()

# Example with input and output
p = Popen("./TestProgram", stdin=PIPE, stdout=PIPE)
out, err = p.communicate("This is the input\n")
print out.rstrip()

The program TestProgram reads one line from stdin and writes it to stdout. I have added the .rstrip() to the output to remove trailing new line characters, for your binary data you probably will not want to do this.

Upvotes: 3

Related Questions