我有一个 python 脚本 script.py
接受命令行参数
我想用 C 做一个包装器,这样我就可以使用 ./script args
调用 script.py
到目前为止,我的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
最佳答案
使用 system()
在这种情况下不必要地复杂化,因为它有效地将给定的命令字符串传递给 (forked) 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为此,如果可能的话。
关于c - 如何运行 python 脚本并在 C 中将参数传递给它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39484159/