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.
pandasandnumpy?