2014-03-13 244 views
2

我正在用C語言和Python編寫一些代碼。將參數傳遞給PyRun_File(***)

我有一個名爲sample.py的Python文件,它接受兩個字符串參數。

我的C程序使用PyRun_SimpleString()調用python函數。這樣我就無法傳遞任何參數。

通過PyRun_SimpleString()

int main(int argc,char *argv[]) 
{ 
...... 
PyRun_SimpleString("import sample\nsample.mainfunc("argv[1]",'Isolated_domU_t')\n"); 
..... 
} 

如何傳遞參數argv[1]使用PyRun_SimpleString(*)

+1

如果你想調用一個函數,你爲什麼要執行一個程序呢?您應該導入'sample'模塊並使用'PyObject_Call *'函數調用函數。 – Bakuriu

+1

它看起來像你不知道如何連接C中的字符串。請看看下面這個問題的SO問題:http://stackoverflow.com/questions/308695/c-string-concatenation – Carsten

回答

0

使用PyRun_String。它有類似PyRun_File簽名:

PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) 

更新:

在你的情況下,對子級是足夠簡單,只需在命令行參數複製到要執行字符串,就像你在你的問題嘗試。您的代碼將無法工作,雖然,因爲這不是你如何串連在C.串試試這個:

#include <Python.h> 
#include <stdio.h> 
#include <string.h> 

int main(int argc, char **argv) { 
    char py[1000]; /* that should be big enough */ 
    strcpy(py, "import sample\nsample.mainfunc("); 
    strcat(py, argv[1]); 
    strcat(py, ",'Isolated_domU_t')\n"); 

    Py_Initialize(); 
    PyRun_SimpleString(py); 
    Py_Finalize(); 
} 

這,當然,只有快速&髒版,不檢查,如果有,即使是傳遞參數到程序,或檢查其長度。

+0

我不是得到(理解)這個語法,所以只有我張貼在這裏。我在哪裏可以得到真實的例子.. :) – Cooldharma06

+0

語法與'PyRun_File'幾乎相同。我以爲你想要一個類似'PyRun_File'的參數。 – Carsten

+0

http://stackoverflow.com/questions/22300349/call-python-function-in-c-code請參考這一個。在那個答案我改變主要addfunction()和該addfunction()[主]我傳遞參數我是如何可以實現那一個。只是在那個答案它作爲一個我必須從命令行 – Cooldharma06

0

可以使用的snprintf或喜歡他的功能 並輸入此

char haies1[2048]; 
snprintf(haies1, sizeof(haies1),"import sample\n" 
       "sample.mainfunc("%s",'Isolated_domU_t')\n",argv[1]) 

然後可以使用PyRun_SimpleString函數這樣

Py_Initialize(); 
PyRun_SimpleString(haies1); 
Py_Finalize();