C通过系统调用执行Python脚本

1 投票
2 回答
1296 浏览
提问于 2025-04-18 14:53

我不知道怎么从我的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

我该怎么办呢?

提前谢谢你!

2 个回答

1

使用 char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL}; 这段代码,和 execv("/usr/bin/python",paramsList); // python 系统调用,成功地运行了一个名为 bla.py 的 Python 脚本。

3

来自Bash的手册页面

-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 };

撰写回答