Quote:
Originally Posted by MrCode
I dunno about Python, but the way I've always done it in C is:
Code:
int main(int argc,char* argv[])
{
if(strcmp(argv[1],"<some argument>"))
do_something(with_parameters);
else if(strcmp(argv[1],"<some other argument>"))
do_something_else(with_different_parameters);
else
printf("Usage: <bla bla bla>\n");
return 0;
}
Is that a bad way of going about it? I've always thought of it as being that argc is the argument count, and argv is the argument variable.
|
Hello MrCode,
Parsing command line arguments is one of the subjects covered in 'how to program 101' so questions relating to 'better parsing of command line arguments' never really come to mind, it's an IF statement right?
For the most part yeah an IF statement will do but once more functionality is added and more and more switches are added the IF statement slowly becomes this huge flying logical spaghetti monster (HFLSM).
That was the main reason I used optparse. I didn't want to code a HFLSM. Here is an example of my code. The application performs black box system tests on a fortran project (SUT), it takes the test files and runs them before checking the result. The command arguments for the testing functionality include the SUT, previous SUTs, and the test files (possiblity a subset based an category and filter)
Parser in the code is the main optparse object (OptionsParser)
Please ignore any grammer errors in the help... work in progress
Code:
def test_command_options(self):
"""
Specifies the parsers command line options when script called with testing command.
"""
self.parser.set_defaults(testing=True)
self.parser.add_option("-e", "--engine", dest="test_engine", help="Specifies the engine that is being tested.")
self.parser.add_option("-a", "--against", "--and-against", action="append", dest="target_engine", help="Specifies the previous engines versions that the test engine will be tested against.")
self.parser.add_option("-c", "--using-category", "--and-category", action="append", dest="target_category", help="Specifies the categories of tests that will be run. All test files contained with in the category will be tested. You can specify more than one category. No errors are raised if any category is not found.")
From the above the script accepts arguments like this...
Code:
app.py test -e 1.23 -a 1.10 -a 1.15 -c "FastTests"
this will test SUT 1.23 against 1.10 and 1.15 using only the test files that are classified as 'FastTests'
or it also supports this
Code:
app.py test --engine 1.23 --against 1.10 --and-against 1.15 --using-category "FastTests"
the command line becomes a mini DSL!! Excellent!
all the above is automatically parsed to data structures so --against and --and-against becomes a list ["1.10", "1.15"]... automagically!! and --help is supported as well.
app.py test --help
will display all the command line arguments and their help; and I haven't written any code to do that. No HFLSMs in sight!!