0

I have a python script script.py which takes command line params

I want to make a wrapper in C so I can call the script.py using ./script args

So far I have this in my script.c file

#include<stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    system("python3.4 script.py");
    return 0;
}

How do I modify the script so I can do ./script arg1 arg2 and the C code executes system("python3.4 script.py arg1 arg2");

I don't have experience in C. Above code is from googling

Krimson
  • 7,386
  • 11
  • 60
  • 97

2 Answers2

2

Using system() is needlessly complicated in this case, as it effectively passes the given command string to (forked) sh -c <command>. This means that you'd have to handle possible quoting of arguments etc. when forming the command string:

 % sh -c 'ls asdf asdf' 
ls: cannot access 'asdf': No such file or directory
ls: cannot access 'asdf': No such file or directory
 % sh -c 'ls "asdf asdf"'
ls: cannot access 'asdf asdf': No such file or directory

Note the difference between the unquoted and quoted versions.

I'd suggest using execve(), if executing the python command is the only purpose of your C program, as the exec family of functions do not return on success. It takes an array of const pointers to char as the new argv, which makes handling arguments easier:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define PYTHON "/usr/bin/python3"
#define SCRIPT "script.py"

int
main(int argc, char *argv[])
{
    /* Reserve enough space for "python3", "script.py", argv[1..] copies
     * and a terminating NULL, 1 + 1 + (argc - 1) + 1 */
    int newargvsize = argc + 2;
    /* VLA could be used here as well. */
    char **newargv = malloc(newargvsize * sizeof(*newargv));
    char *newenv[] = { NULL };

    newargv[0] = PYTHON;
    newargv[1] = SCRIPT;
    /* execve requires a NULL terminated argv */
    newargv[newargvsize - 1] = NULL;
    /* Copy over argv[1..] */
    memcpy(&newargv[2], &argv[1], (argc - 1) * sizeof(*newargv));
    /* execve does not return on success */
    execve(PYTHON, newargv, newenv);
    perror("execve");
    exit(EXIT_FAILURE);
}

As pointed out by others, you should use the official APIs for this, if at all possible.

Community
  • 1
  • 1
Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
0

You can generate your command as a string. You just need to loop through argv[] to append each parameters given to the C program at then end of your command string. Then you can use your command string as the argument for the system() function.