Michael 1022
Michael 1022

Reputation: 91

Calling a C/C++ code from Python with an argument

I read similar posts but nothing specific to this. Or maybe my logic is incorrect and you can correct me please.

What I'm trying to do:

Write python code, that then calls an already compiled C or C++ code. But how would I pass an argument to that C/C++ script given that it's already been compiled?

I have a program in Python that manipulates an Excel file. And then at some point I need to search through, append, and create an array of 10,000 cells. I figured C/C++ would make this faster since python is taking some time to do that.

Help please.

Upvotes: 2

Views: 4055

Answers (1)

hmofrad
hmofrad

Reputation: 1902

Let's say we want to write a Python script that acts as a wrapper on top of a C binary and passes arguments from the terminal to the C binary. first, create a test.c C program as follows:

#include <stdio.h>

int main(int argc, char *argv[])
{
   if(argc > 1)
   {
      int i;
      printf("C binary: ");
      for(i = 0; i < argc; i++)
         printf("%s ", argv[i]);
      printf("\n");
   }
   else
      printf("%s: No argument is provided!\n", argv[0]);
   return(0);
}

then compile it using:

gcc -o test test.c

and run it for two dummy arguments using:

./test arg1 arg2

Now, going back to your question. How I could pass arguments from Python to a C binary. First you need a Python script to read the arguments from the terminal. The test.py would do that for you:

import os
import sys

argc = len(sys.argv)
argv =  sys.argv

if argc > 2:
   cmd = './'
   for i in range(1,argc):
      cmd = cmd + argv[i] + ' '
   if os.path.isfile(argv[1]):
      print('Python script: ', cmd)
      os.system(cmd)
   else:
      print('Binary file does not exist')
      bin = 'gcc -o ' + argv[1] + ' '+ argv[1] + '.c'
      print(bin)
      os.system(bin)
      if os.path.isfile(argv[1]):
         os.system(cmd)
      else:
         print('Binary source does not exist')
         exit(0)
else:
   print('USAGE: python3.4', argv[0], " BINARY_FILE INPUT_ARGS");
   exit(0)

Having test.c and test.py in the same directory. Now, you can pass arguments from the terminal to the test C binary using:

python3.4 test.py test arg1 arg2

Finally, the output would be:

Python script:  ./test arg1 arg2
C binary: ./test arg1 arg2

Two last remarks:

  • Even if you don't compile the source code, the test.py will look for the test.c source file and try to compile it.
  • If you don't want to pass arguments from the terminal, you can always define the arguments in the Python script and pass them to the C binary.

Upvotes: 2

Related Questions