gpt4 book ai didi

python - 如何在 C 代码中返回 pyrun_simplefile 的输出

转载 作者:太空狗 更新时间:2023-10-29 21:19:06 25 4
gpt4 key购买 nike

代码是

{
char name[MAX_JSON_FIELD];
FILE *fp;
copy_cJSON(name,objs[0]);
if ( (fp= fopen(name, "r")) != 0 )
{
Py_Initialize();
PyRun_SimpleFile(fp, name);
Py_Finalize();
fclose(fp);
}
return(clonestr("return string"));
}

如何让它返回 python 文件的输出而不是打印它?

最佳答案

I achieved this using a huge workaround. I made both C and Python read and write into a file. I didn't find a better option yet.

我找到了一个实际的解决方案。它由 2 个文件组成:“main.c”打开脚本文件“script.py”,它比较两个字符串(此处:“Hello”和“Mars”)并返回较长的一个。我仍然觉得奇怪,它需要大约 20 个命令才能实现这一点,也许有更好的解决方案。

[主.c]

    //compile me with "gcc main.c -I/usr/include/python2.7 -lpython2.7"
//original source: "http://python.haas.homelinux.net/python_kapitel_26_003.htm"
//owner is Peter Kaiser and Johannes Ernesti who published the Book "Python" under Galileo Computing
//Translation from german with many additional (and very unprofessional) comments and slight adaption by Cupacoffee, 17.02.2015.
//bugs, grammar mistakes and wrong explainations are my contribution

#include <Python.h>

int main (int argc, char *argv[])
{

char *result;//This char will receive the return value.

PyObject *module, *func, *prm, *ret;//These are some helping variables i don't understand.

Py_Initialize();

PySys_SetPath(".");//Sets the working path to the current path

module = PyImport_ImportModule("script");//Import of the script-file, note that the actual script name is "script.py"!

if (module != 0)//Asks if the script was loaded at all.
{
func = PyObject_GetAttrString(module, "compare_function");//Opens a function within the python script. Notice that you must use a function within the python script, because otherwise you can't return anything.
prm = Py_BuildValue("(ss)", "Hello", "Mars");//The "(ss)" means two strings are passed (replace with "i" for integer for instance), the "Hello" and "Mars" are the strings i pass to the script.
ret = PyObject_CallObject(func, prm);//Returns some python object i have literally no idea about ...

result = PyString_AsString(ret);// ... but luckily there's a function to cast it back to a c-compatible char*!
printf("The Script decdided that '%s' is longer!",result);

Py_DECREF(module);//cleanup?
Py_DECREF(func);//cleanup?
Py_DECREF(prm);//cleanup?
Py_DECREF(ret);//cleanup?
}

else//No script found
{
printf("Error: No script file named \"script.py\" was found!\n");
}

Py_Finalize();
return 0;
}

[脚本.py]

    def compare_function(a, b):#this function takes 2 parameters, they are strings
return (a if min(a) < min(b) else b)#they get compared and returned to the c-program

祝你好运。

*提示,我花了 2 个多小时来格式化此文本以便我可以发布它。*

关于python - 如何在 C 代码中返回 pyrun_simplefile 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com