2014-07-26 54 views
1

我無法弄清楚如何從C代碼執行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腳本的開頭添加一行:

#!/usr/bin/python 

我能做些什麼?

預先感謝您

+0

你可以跳過bash的通話完全,只是調用Python,如[這裏](HTTPS ://gist.github.com/miku/499c5bd2b903d6885448#file-snippet-c-L9)? – miku

回答

3

從猛砸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. 

例如

$ 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

使用char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL};execv("/usr/bin/python",paramsList); // python system call造成命名爲python腳本成功調用bla.py

相關問題