2015-02-10 19 views
3

的代碼是如何從pyrun_simplefile C代碼返回輸出

{ 
    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文件的輸出,而不是打印出來的?

+1

停止使用最高級別的功能。 – 2015-02-10 18:03:44

+1

另外,我不確定「Return Output」的含義。 Python模塊本身不會「返回」任何東西,所以你可能意味着要在該文件中執行特定的功能,並獲得它的結果。你也可以使用各種'PySys_'函數,但是我懷疑這是你實際打算的 – 2015-02-10 22:09:25

回答

2

我使用巨大的解決方法實現了這一點。我將C和Python都讀取並寫入文件。我還沒有找到更好的選擇。

我找到了一個實際的解決方案。它由2個文件組成:「main.c」打開腳本文件「script.py」,它比較兩個字符串(這裏是:「Hello」和「Mars」)並返回較長的一個。我仍然感到奇怪的是,要達到這個目標需要20個指令,也許還有更好的解決方案。

[main.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; 
    } 

[script.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個多小時到這個文本的格式,所以我可以將它張貼。*

1

我的一個朋友給了我一些代碼片段其回答的問題。我不想編輯舊帖子,因爲這兩個程序是全新的方法;一個用C語言編寫,一個用C++編寫。兩者都使用相同的Python腳本。

他還指出我的「system」[Unix:「man system」]和「popen」[Unix:「man popen」]的手冊頁。第二個允許交互式溝通,稍後可能會有用。

[C-文件:]

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 

int callScript() 
{ 
    char *cmd = "./script.py hello world"; 
    return WEXITSTATUS(system(cmd)); 
} 

int main(int argc, char *argv[]) 
{ 
    printf("main - argc: %d, arguments:\n", argc); 
    for (int i = 0; i < argc; i++) 
     printf("\targv[%d]: %s\n", i, argv[i]); 

    int ret = callScript(); 
    printf("exit code of script %d\n", ret); 

    return 0; 
} 

[C++ - 文件:]

#include <string> 
#include <sstream> 
#include <iostream> 
#include <stdlib.h> 
#include <sys/wait.h> 

int callScript(std::string args) 
{ 
    std::string cmd = "./script.py" + args; 
    int ret = system(cmd.c_str()); 
    return WEXITSTATUS(ret); 
} 

int main(int argc, char *argv[]) 
{ 
    std::cout << "main - argc: " << argc << ", arguments:" << std::endl; 
    std::stringstream args; 
    for (int i = 0; i < argc; i++) 
    { 
     std::cout << "\targv[" << i << "]: " << argv[i] << std::endl; 
     if (i) 
      args << " " << argv[i]; 
    } 

    int ret = callScript(args.str()); 
    std::cout << "exit code of script " << ret << std::endl; 

    return 0; 
} 

[Python的腳本:]

#!/usr/bin/env python 

import sys 

def Hello(person): 
    print "Hello " + person 

def PrintArgs(argv): 
    for arg in argv: 
     print arg 

if __name__ == "__main__": 
    Hello("World!") 
    PrintArgs(sys.argv[1:]) 
    sys.exit(2)