2016-09-14 57 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()函数的参数。