Linux中父Python和C子进程之间的通信

时间:2013-09-17 06:12:07

标签: python c linux ipc

我正在开发一个Python应用程序,它需要不时地生成子进程(用C语言编写),以便为它提供一些二进制数据并获得回复。子进程只在需要时生成,并且只提供一个请求。我有什么选择?使用stdin / stdout是否安全?

1 个答案:

答案 0 :(得分:3)

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()

程序TestProgramstdin读取一行并将其写入stdout。我已将.rstrip()添加到输出中以删除尾随的新行字符,对于二进制数据,您可能不希望这样做。