python - 如何使用 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 代码的返回值?
解决方案
不久前我在子处理模块上写了一个演示来解决这个问题。
这是我使用的示例:
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,您可以按照这个问题的答案。
推荐阅读
- python - 检测颜色以外的颜色检测输出颜色
- hololens - HoloLens:动态环境中的空间感知
- docker - Docker 抛出错误:每当我尝试构建 GetTogether 时出现无法满足的约束
- java - 有没有办法将 textview 中的文本标题识别为 Android Studio for Java 中的 ID?
- stdout - 如何从 Dyalog APL 访问标准输出流 (stdout)
- java - 如何存储识别出的人脸,以便在应用程序关闭时和在不同设备上使用它们
- html-table - 在 MDX 中查找与目标的销售比率
- javascript - 如何自定义脚本以在单个页面上工作
- php - 一个使用 HTML 表单的 php 中的简单数字猜测程序
- mysql - 尝试在空对象引用上调用虚拟方法 getDatabasePath(java.lang.String)'