2016-09-14 26 views
0

運行Python腳本,將參數傳遞給它,我有一個python腳本script.py這需要命令行PARAMS如何用C

我想要在C包裝,所以我可以在script.py使用調用./script args

到目前爲止,我有這在我的script.c文件

#include<stdio.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]){ 
    system("python3.4 script.py"); 
    return 0; 
} 

如何修改劇本,所以我可以做./script arg1 arg2和C代碼執行system("python3.4 script.py arg1 arg2");

我沒有C語言經驗。以上代碼來自Google搜索

回答

2

使用system()在這種情況下是不必要的複雜,因爲它實際上將給定的命令字符串傳遞給(分叉)sh -c <command>。這意味着,你不得不處理可能形成的命令字符串時的參數等報價:

% sh -c 'ls asdf asdf' 
ls: cannot access 'asdf': No such file or directory 
ls: cannot access 'asdf': No such file or directory 
% sh -c 'ls "asdf asdf"' 
ls: cannot access 'asdf asdf': No such file or directory 

注未加引號,並引述版本之間的差異。

我建議使用execve(),如果執行python命令是你的C程序的唯一目的,因爲exec函數家族不會成功返回。這需要常量數組的指針爲char作爲新ARGV,這使得操作更簡單的參數:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 

#define PYTHON "/usr/bin/python3" 
#define SCRIPT "script.py" 

int 
main(int argc, char *argv[]) 
{ 
    /* Reserve enough space for "python3", "script.py", argv[1..] copies 
    * and a terminating NULL, 1 + 1 + (argc - 1) + 1 */ 
    int newargvsize = argc + 2; 
    /* VLA could be used here as well. */ 
    char **newargv = malloc(newargvsize * sizeof(*newargv)); 
    char *newenv[] = { NULL }; 

    newargv[0] = PYTHON; 
    newargv[1] = SCRIPT; 
    /* execve requires a NULL terminated argv */ 
    newargv[newargvsize - 1] = NULL; 
    /* Copy over argv[1..] */ 
    memcpy(&newargv[2], &argv[1], (argc - 1) * sizeof(*newargv)); 
    /* execve does not return on success */ 
    execve(PYTHON, newargv, newenv); 
    perror("execve"); 
    exit(EXIT_FAILURE); 
} 

正如其他人所指出的,您還是應該在所有可能使用official APIs此。

0

您可以將您的命令作爲字符串生成。你只需要通過argv []循環來在命令字符串的末尾追加提供給C程序的每個參數。然後你可以使用你的命令字符串作爲system()函數的參數。