Krimson Krimson - 1 month ago 4x
C Question

How do I run a python script and pass arguments to it in C

I have a python script
which takes command line params

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

So far I have this in my

#include <stdlib.h>

int main(int argc, char *argv[]){
return 0;

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

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


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 ""

main(int argc, char *argv[])
    /* Reserve enough space for "python3", "", 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);

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