Python的运行C程序,然后捕获输出 [英] Run C program from Python and then capture output
问题描述
可能重复:结果
如何连接一个Python和C程序?
块引用>我有一个C程序,它有两个参数并输出一个数字。
./ a.out的2 3(例如)。它确实有些昂贵的计算操作,所以我想知道我可以使用Python的多库运行一堆C程序,然后编译所有的数字到一个列表或表或者一些数据结构?
谢谢,
这是不是重复,因为我的问题是我怎么能做到这一点并行EX。许多线程!
解决方案//你的C文件是从所谓的蟒蛇
//编译:
// GCC -dynamiclib -I / usr / include目录/ python2.7 / -lpython2.7 -o Module.dylib的module.c#包括LT&; Python.h>静态的PyObject * py_myFunction(*的PyObject自我,*的PyObject参数)
{
的char * s =你好从C!;
返回Py_BuildValue(S,S);
}静态PyMethodDef myModule_methods [] = {
{myFunction的py_myFunction,METH_VARAGS},
{NULL,NULL}
};无效initmyModule()
{
(无效)Py_InitModule(MyModule的myModule_methods);
}要从蟒蛇拨打:
从模块中导入*
从myFunction的结果:打印,myFunction的()Possible Duplicate:
How do I connect a Python and a C program?I have a C program that takes two args and outputs a number.
./a.out 2 3 (for example). It does some computational expensive operations, so I was wondering could I use Python's multiprocessing library to run a bunch of the C programs and then compile all the numbers into a list or table or some data structure?
Thanks,
This is not a duplicate because my questions is how can i do it IN PARALLEL EX. MANY THREADS!
解决方案// Your C file to be called from python // To compile : // gcc -dynamiclib -I/usr/include/python2.7/ -lpython2.7 -o Module.dylib Module.c #include < Python.h > static PyObject* py_myFunction(PyObject* self, PyObject* args) { char *s = "Hello from C!"; return Py_BuildValue("s", s); } static PyMethodDef myModule_methods[] = { {"myFunction", py_myFunction, METH_VARAGS}, {NULL, NULL} }; void initmyModule() { (void) Py_InitModule("myModule", myModule_methods); }
To call from python:
from Module import * print "Result from myFunction:", myFunction()
这篇关于Python的运行C程序,然后捕获输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!