I cannot figure out how I can execute a python script from my C code. I read that I can embed the python code inside C, but I want simply to launch a python script as if I execute it from command line. I tried with the following code:
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);
}
I don't know where the error is since if I replace the call to python script with the call to another executable, it works well. I have added at the beginning of my python script the line:
#!/usr/bin/python
What can I do?
Thank you in advance
From the 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.
Eg
$ bash -c 'echo x $0 $1 $2' foo bar baz
x foo bar baz
You, however don't want to assign to the positional parameters, so change your paramList
to
char * paramsList[] = { "/bin/bash", "-c",
"/usr/bin/python /home/mypython.py", NULL };
Using char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL};
and execv("/usr/bin/python",paramsList); // python system call
execv("/usr/bin/python",paramsList); // python system call
caused a successful invocation of the python script named bla.py
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.