Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...