【问题标题】:Popen from python to Cpp processPopen从python到Cpp进程
【发布时间】:2022-11-24 01:25:32
【问题描述】:

我正在尝试创建一个Python将lines发送到cpp文件在 while 循环上运行并将接收到的行打印到控制台中。

测试.py

#test.py
import subprocess

p = subprocess.Popen('./stdin.out',bufsize=1,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, universal_newlines=True)

p.stdin.write('hello world\n')
p.stdin.write('hell world\n')
p.stdin.write('hel world\n')

p.terminate()

标准输入.cpp

//stdin.cpp
#include <iostream>

int main(){
  std::string line;
  std::cout << "Hello World! from C++" << std::endl;
  while (getline(std::cin, line)) {
    std::cout <<"Received from python:" << line << std::endl;
  }
  return 0;
}

这是可以实现的吗?

【问题讨论】:

  • 什么地方出了错?代替 p.terminate(),您可能需要 p.stdin.close() 后接 p.wait()。
  • 它不会向 cpp bin 发送任何内容,也不会向控制台打印任何内容
  • 我认为你在 cpp 程序有机会做任何事情之前就终止了它。
  • 如何不终止程序。我在 cpp 上也尝试过一段时间,但我什至无法打印任何东西

标签: python c++ subprocess


【解决方案1】:

你有两个问题。第一个是 python 脚本在它有机会运行之前终止子进程。第二个是您将 stdout 和 err 通过管道传输到 DEVNULL,因此即使它运行了,您也看不到任何东西。通常,当您完成与子进程的通信时,您会关闭标准输入。子进程可以随意读取标准输入,并在输入结束时自然地发现关闭。然后等待它退出。

#!/usr/bin/env python3
#test.py
import subprocess

p = subprocess.Popen('./wc',bufsize=1,stdin=subprocess.PIPE, universal_newlines=True)

p.stdin.write('hello world
')
p.stdin.write('hell world
')
p.stdin.write('hel world
')
p.stdin.close()
p.wait()

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 2021-12-27
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2011-08-05
    • 2017-02-03
    • 2017-08-22
    相关资源
    最近更新 更多