You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过Python脚本向运行while循环的C++程序发送行内容并打印?

需求可实现,当前代码需调整

你的需求完全可以实现,但现有代码存在几个关键问题导致无法正常运行:

问题点

  • Python脚本中将C程序的stdout和stderr设为subprocess.DEVNULL,导致你看不到C程序的输出内容
  • 写入数据后未刷新标准输入缓冲区,数据可能还没传递给C++程序就被强制终止
  • 直接调用terminate()强制终止进程,C++程序可能还没处理完接收的数据就被中断

修正后的代码

test.py

# test.py
import subprocess

# 保留stdout/stderr,让C++程序的输出直接显示在控制台
p = subprocess.Popen(
    './stdin.out',
    bufsize=1,
    stdin=subprocess.PIPE,
    stdout=None,
    stderr=None,
    universal_newlines=True
)

# 发送行数据
p.stdin.write('hello world\n')
p.stdin.write('hell world\n')
p.stdin.write('hel world\n')

# 刷新缓冲区,确保数据全部发送给C++程序
p.stdin.flush()
# 关闭stdin,让C++程序检测到EOF并退出while循环
p.stdin.close()
# 等待C++进程自然结束
p.wait()

stdin.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;
}

运行步骤

  1. 编译C++程序:
    # Linux/macOS
    g++ stdin.cpp -o stdin.out
    # Windows(需安装MinGW等编译工具)
    g++ stdin.cpp -o stdin.exe
    
  2. 运行Python脚本,控制台会输出:
    Hello World! from C++
    Received from python:hello world
    Received from python:hell world
    Received from python:hel world
    

内容的提问来源于stack exchange,提问作者Pedro Mendes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:05:27