我不知道如何从我的C代码中执行python脚本。我读到可以将python代码嵌入到C中,但我只想像从命令行执行一样启动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
我能做什么?
提前谢谢你
最佳答案
从舞会上:
-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.
例如。
$ 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 };