首页 > 解决方案 > 如何使用 python 运行 C 文件?

问题描述

我需要从我的 python 程序运行一个 C 文件。我也想从我的程序中传递参数。我希望将输出返回到我的 python 程序中。

我在 c 代码上尝试过的简单示例:

#include<stdio.h>
int main(){
int a=2;
return a;
}

在我的 jupyter 笔记本中,我尝试过:

import subprocess as sb
sb.call(["g++","random.c"],shell=True)  ##random.c is the C file.
sb.call("./a.out",shell=True)

我得到的输出状态为 1(我猜是一些错误)。如何获取 C 代码的返回值?

标签: pythonc

解决方案


不久前我在子处理模块上写了一个演示来解决这个问题。

这是我使用的示例:

import os # Used to determine if machine is windows or unix/macOS
import subprocess # Used to run commands from python

def compile(filename, binary_filename):
    """Function to compile the provided file in gcc"""
    # Below is equivalent to running: gcc -o hello_world hello_world.c
    print(f"Creating binary: {binary_filename} From source file: {filename}\n")
    subprocess.run(["gcc", "-o", binary_filename, filename])

def run_binary(binary_filename):
    """Runs the provided binary"""
    print(f"Running binary: {binary_filename}\n")
    subprocess.run([binary_filename])

if __name__ == "__main__":
    compile("hello_world.c", "hello_world")

    if os.name =="nt": # If on windows
        run_binary("hello_world.exe")

    else: # If on unix/mac
        run_binary("hello_world")

    print("Binary run")

我认为这回答了你的问题,如果你想从 python 调用 C 代码,你将需要ctypes library

如果您想另辟蹊径,从 C 代码运行 python,您可以按照这个问题的答案。


推荐阅读