简体   繁体   English

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

[英]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. 我正在开发一个Python应用程序,该应用程序需要不时产生一个子进程(用C编写),以为其提供一些二进制数据并获得答复。 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? 使用stdin / stdout安全吗?

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 . 程序TestProgramstdin读取一行并将其写入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. 我已经将.rstrip()添加到输出中,以删除结尾的换行符,对于您的二进制数据,您可能不想这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM