C通过系统执行python脚本

2024-06-25 06:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何从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脚本的开头添加了一行:

^{pr2}$

我能做什么?在

提前谢谢你


Tags: 代码脚本bashifbinforkelseerr
2条回答

使用char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL};execv("/usr/bin/python",paramsList); // python system call可以成功调用名为的python脚本废话

从Bashman 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.

例如

$ bash -c 'echo x $0 $1 $2' foo bar baz
x foo bar baz

但是,您不想分配给位置参数,所以将paramList更改为

^{pr2}$

相关问题 更多 >