【问题标题】:Communication between a Python parent and C child processes in LinuxLinux 中 Python 父进程和 C 子进程之间的通信
【发布时间】:2013-09-17 06:12:07
【问题描述】:

我正在开发一个 Python 应用程序,它需要不时产生一个子进程(用 C 编写),向它提供一些二进制数据并获得回复。子进程只会在需要时生成,并且只会服务一个请求。我在这里有什么选择?使用 stdin/stdout 安全吗?

【问题讨论】:

标签: python c linux ipc


【解决方案1】:
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() 添加到输出中以删除尾随的换行符,对于您的二进制数据,您可能不想这样做。

【讨论】:

  • 在我的脑海中,你可以通过 Popen(["echo", "This is a test"], ...) 删除 shell=True。通常,将命令和参数分开到单独的列表元素中,例如["ls","-l","/"]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 2017-12-19
相关资源
最近更新 更多