I'm writing a python script to run a compiled binary whose source was written in C++, varying a parameter as controlled using a command line argument.
e.g. os.system("./my_program " + my_arg)
Let's say it's too much hassle changing this parameter from main()
.
Instead I'd like to set it in some included header file using
#define MY_PARAM my_val
where my_val
is taken as a command line argument when the program is run.
I'm using gcc to compile
Any ideas?
Based on your code snippet:
os.system("./my_program " + my_arg)
You're just trying to send an argument input to your program. You don't need to use preprocessor definitions (e.g. #define SOMETHING
) for it. (In fact, you can't, because the binary has already been built.)
Instead, you modify your main
function from int main()
to int main(int argc, char *argv[])
.
You'd use it in a way similar to what's below:
#include <iostream>
int main(int argc, char *argv[]) {
for(int i = 0; i < argc; ++i)
std::cout << "Argument " << i << ": " << argv[i] << std::endl;
return 0;
}
Sample runs from the code above, which was placed in the test.cpp
file and used from the Python3 interactive interpreter:
➜ /tmp g++ test.cpp -o argtest
➜ /tmp ./argtest
Argument 0: ./argtest
➜ /tmp ./argtest a b c d e 123
Argument 0: ./argtest
Argument 1: a
Argument 2: b
Argument 3: c
Argument 4: d
Argument 5: e
Argument 6: 123
➜ /tmp python3
Python 3.4.3+ (default, Oct 14 2015, 16:03:50)
[GCC 5.2.1 20151010] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import system
>>> system('./argtest a b c 123')
Argument 0: ./argtest
Argument 1: a
Argument 2: b
Argument 3: c
Argument 4: 123
0
>>>
The zero at the end is the return code from Python's system
call saying everything went fine.
Dumb question. I guess I didn't properly understand the problem I was trying to solve before asking! I got past this problem by:
Adding optional arguments in the makefile using the -D option to set these compile-time variables. This replaces specified variable names with the values given when running make
.
A python script looped through a bunch of options, each time calling os.system("make OPT1=" + str(opt1) + "OPT2=" + str(opt2))
etc. followed by os.system("./myprog | tee mylogfile.log")
The python script then parsed the logfile, which contained output that varied as a function of the options inputted as arguments to make
.
Hope this helps anyone wanting to do something similar.