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

如何从Python代码向C代码传递参数及输入数据?

解决向C程序传递文本输入的问题

一、修正Python代码的核心问题

你的原代码存在两个关键错误:

  • 错误尝试直接运行C源文件main.c,实际应该运行编译后的可执行文件
  • Python3中subprocess.Popen.communicate()的输入必须是字节类型,不能直接传字符串

修正后的Python代码:

import subprocess  
from subprocess import Popen, PIPE, STDOUT

print("This is read by py!")
# 编译C文件,指定输出文件名避免默认的a.exe混淆,-Wall可显示编译警告
subprocess.call(["gcc", "main.c", "-Wall", "-o", "text_processor"])
# 运行编译后的可执行文件,而非源文件
p = Popen(['./text_processor'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
# 将字符串编码为字节流传递给C程序的标准输入
stdout_data = p.communicate(input=b'div')[0]
# 将C程序返回的字节结果转成字符串输出
print("C程序处理结果:")
print(stdout_data.decode('utf-8'))

print("Done")

二、编写适配的C程序(main.c)

C程序需要通过**标准输入(stdin)读取Python传递的文本,处理后再通过标准输出(stdout)**返回结果,示例代码如下(以文本转大写为例):

#include <stdio.h>
#include <ctype.h>

int main() {
    char input_buf[1024];
    // 从标准输入读取文本
    if (fgets(input_buf, sizeof(input_buf), stdin) != NULL) {
        // 处理逻辑:将输入文本转为大写
        for (int i = 0; input_buf[i] != '\0'; i++) {
            input_buf[i] = toupper(input_buf[i]);
        }
        // 将处理结果输出到标准输出
        printf("%s", input_buf);
    }
    return 0;
}

三、关键注意事项

  • 若要传递命令行参数(而非流式文本输入),可直接在Popen的参数列表中添加,比如Popen(['./text_processor', 'arg1', 'arg2']),C程序通过argc和argv获取这些参数
  • 编译C文件时指定输出文件名(-o text_processor)是更规范的做法,避免多个编译产物混淆
  • Python传递输入时,若涉及中文等非ASCII字符,需明确指定编码,比如input='中文文本'.encode('utf-8')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:50:49