我无法弄清楚如何从C代码中执行python脚本。我读到我可以在C中嵌入python代码,但我想简单地启动一个python脚本,就像我从命令行执行它一样。我尝试使用以下代码:
char * paramsList[] = {"/bin/bash", "-c", "/usr/bin/python", "/home/mypython.py",NULL};
pid_t pid1, pid2;
int status;
pid1 = fork();
if(pid1 == -1)
{
char err[]="First fork failed";
die(err,strerror(errno));
}
else if(pid1 == 0)
{
pid2 = fork();
if(pid2 == -1)
{
char err[]="Second fork failed";
die(err,strerror(errno));
}
else if(pid2 == 0)
{
int id = setsid();
if(id < 0)
{
char err[]="Failed to become a session leader while daemonising";
die(err,strerror(errno));
}
if (chdir("/") == -1)
{
char err[]="Failed to change working directory while daemonising";
die(err,strerror(errno));
}
umask(0);
execv("/bin/bash",paramsList); // python system call
}
else
{
exit(EXIT_SUCCESS);
}
}
else
{
waitpid(pid1, &status, 0);
}
我不知道错误在哪里,因为如果我用对另一个可执行文件的调用替换对python脚本的调用,它运行良好。 我在我的python脚本的开头添加了一行:
#!/usr/bin/python
我该怎么办?
提前谢谢
答案 0 :(得分:3)
来自Bash man page:
-c string If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.
E.g。
$ bash -c 'echo x $0 $1 $2' foo bar baz
x foo bar baz
但是,您不想分配位置参数,因此请将paramList
更改为
char * paramsList[] = { "/bin/bash", "-c",
"/usr/bin/python /home/mypython.py", NULL };
答案 1 :(得分:1)
使用char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL};
和execv("/usr/bin/python",paramsList); // python system call
成功调用名为 bla.py