2014-07-26 8 views
1

Je n'arrive pas à comprendre comment je peux exécuter un script python à partir de mon code C. J'ai lu que je peux intégrer le code python dans C, mais je veux simplement lancer un script python comme si je l'exécutais à partir de la ligne de commande. J'ai essayé avec le code suivant:C exécuter un script python via un appel système

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

Je ne sais pas où l'erreur est depuis si je remplace l'appel à script python avec l'appel à un autre exécutable, il fonctionne bien. J'ai ajouté au début de mon script python la ligne:

#!/usr/bin/python 

Que puis-je faire?

Nous vous remercions à l'avance

+0

Pouvez-vous sauter le tout appel bash et il suffit d'appeler python, comme [ce] (https : //gist.github.com/miku/499c5bd2b903d6885448#file-snippet-c-L9)? – miku

Répondre

3

De 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. 

Par exemple

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

Vous, mais ne voulez pas attribuer aux paramètres de position, donc changer votre paramList à

char * paramsList[] = { "/bin/bash", "-c", 
         "/usr/bin/python /home/mypython.py", NULL }; 
1

En utilisant char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL}; et execv("/usr/bin/python",paramsList); // python system call a provoqué une invocation réussie du script python nommé bla.py

Questions connexes