How to analyse .exe parameters inside the program?

I have a program that can have a lot of parameters (we have over +30 differents options).

Example: myProgram.exe -t alpha 1 -prod 1 2 -sleep 200

This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.

For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.

Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?

The code is in C# but I think the logic can be any other language too...


Asked by: Patrick495 | Posted: 30-11-2021






Answer 1

(Well, since this is tagged with Python):

We use Python's optparse module for this purpose. It has a much friendlier API than lots of ifs.

Answered by: Briony199 | Posted: 01-01-2022



Answer 2

Create a hash table which stores function pointers (in C# that'd be delegates) for handling each of the parameters, keyed using the parameter text. Then you just go through the command line in a loop and make calls to delegates based on what comes out of hash table lookups.

Answered by: Roland566 | Posted: 01-01-2022



Answer 3

A useful options library for C#: NDesk.Options

Answered by: Arnold100 | Posted: 01-01-2022



Answer 4

The getopt function is very common for C programming. It can parse parameters for you. Here is a question (and answer) where to get it for C#: GetOpt library for C# .

Especially lappies implementation looks like rather modern C# with attributes and such.

Answered by: Chester861 | Posted: 01-01-2022



Answer 5

I'd be a little uncomfortable using a command line like that. First thing I'd say is "what does the first '1' mean, and why is it different to the second '1'?"

Any time I write a command line utility that accepts an argument, I consider how easy it would be for a user to learn all the options. In this case, it looks like a bit of a hard task, IMHO.

Maybe refactoring how the user passes the arguments would be a good idea. There's a reason why a lot of software takes key/value type parameters (e.g. myclient.exe -server=myServerName -config=debug) It takes a lot of load off the user, and also simplifies the argument parsing once it hits your code.

Answered by: Brooke759 | Posted: 01-01-2022



Answer 6

Just for fun, you can create a wrapper around the whole thing and work with strong names in your code. More work? Yes. But more fun and once you add a new command to the wrapper you can forget about it ;)

public class Form1 
{ 

private void main() 
{ 
    MyCommandHandler CommandLineHandler = new MyCommandHandler(); 
    CommandLineHandler.SetInput = "-t alpha 1 -prod 1 2 -sleep 200"; 

    //now we can use strong name to work with the variables: 
    //CommandLineHandler.prod.ProdID 
    //CommandLineHandler.prod.ProdInstanceID 
    //CommandLineHandler.Alpha.AlhaValue() 
    //CommandLineHandler.Sleep.Miliseconds() 
    if (CommandLineHandler.Alpha.AlhaValue > 255) { 
        throw new Exception("Apha value out of bounds!"); 
    } 

} 
} 

public class MyCommandHandler 
{ 
private string[] values; 
public string SetInput { 
    set { values = Strings.Split(value, "-"); } 
} 

//Handle Prod command 
public struct prodstructure 
{ 
    public string ProdID; 
    public string ProdInstanceID; 
} 
public prodstructure prod { 
    get { 
        prodstructure ret = new prodstructure(); 
        ret.ProdID = GetArgsForCommand("prod", 0); 
        ret.ProdInstanceID = GetArgsForCommand("prod", 1); 
        return ret; 
    } 
} 

//Handle Apha command 
public struct Aphastructure 
{ 
    public int AlhaValue; 
} 
public Aphastructure Alpha { 
    get { 
        Aphastructure ret = new Aphastructure(); 
        ret.AlhaValue = Convert.ToInt32(GetArgsForCommand("alpha", 0)); 
        return ret; 
    } 
} 


//Handle Sleep command 
public struct SleepStructure 
{ 
    public int Miliseconds; 
} 
public SleepStructure Sleep { 
    get { 
        SleepStructure ret = new SleepStructure(); 
        ret.Miliseconds = Convert.ToInt32(GetArgsForCommand("sleep", 0)); 
        return ret; 
    } 
} 


private string GetArgsForCommand(string key, int item) 
{ 
    foreach (string c in values) { 
        foreach (string cc in Strings.Split(c.Trim, " ")) { 
            if (cc.ToLower == key.ToLower) { 
                try { 
                    return Strings.Split(c.Trim, " ")(item + 1); 
                } 
                catch (Exception ex) { 
                    return ""; 
                } 
            } 
        } 
    } 
    return ""; 
} 
} 

Answered by: Catherine318 | Posted: 01-01-2022



Answer 7

The answer in Java, as is so often the case, is that someone has beaten you to it and released an excellent open source library to do this. Have a look at Apache CLI.

Answered by: Catherine222 | Posted: 01-01-2022



Answer 8

I dont think this is too cludging..

private void Main() 
{ 
string c = "-t alpha 1 -prod 1 2 -sleep 200"; 

foreach (string incommand in Strings.Split(c, "-")) { 
    HandleCommand(Strings.Split(incommand.Trim, " ")); 
} 
} 


public void HandleCommand(string[] c) 
{ 
switch (c(0).ToLower) { 
    case "t": 
        Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); 
        break; 
    case "prod": 
        Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); 
        break; 
    case "sleep": 
        Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); 
        break; 
} 
} 

Of course, instead of doing exactly same thing in those switch-statements, call appropriate functions or code.

Answered by: Sawyer133 | Posted: 01-01-2022



Answer 9

Commonly, you can replace large if/else or switch/case constructs with a Dictionary. Where the if-criteria is the key and the code to execute is the value.

For example, you could nave a Dictionary<string, ICommand> (or Dictionary<string, Type>), which you fill before you parse your command line.

When you iterate over the passed in command line options, you simply look them up in the dictionary and "invoke" on the value which is the matching command (object) to execute (or alternatively use Activate.CreateInstance(/*dictionary-value*/) if you stored the type instead of a specific object instance).

In C# 3.0 you could also something like Dictionary<string, System.Linq.Expressions.Expression<T>>, although this gets you pretty close to the actual if-statement - which is something you might want to have or not. YMMV.

Some libraries provide you with the mere parsing of the command line arguments (like traditionally getopt() et al did) or can provide the whole package, including the invokation of actions upon the presence of specific command line arguments.

Answered by: Stuart580 | Posted: 01-01-2022



Similar questions

python - Django: Arbitrary number of unnamed urls.py parameters

I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: /browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... where 'name' maps to a model attribute and 'value' is the search criteria for that...


python - variables as parameters in field options

I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this: home = models.ForeignKey(Team, editable=lambda self: True if self.id else False) But it doesn't work. Maybe something with overriding the init can help me, but i don't sure what can do the trick. I know i can check for self.id...


python - Default parameters to actions with Django

Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django? urlpatterns = patterns('',(r'^test/(?P&lt;name&gt;.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving...


python - Loop function parameters for sanity check

I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to ...


python - How can I pass all the parameters to a decorator?

I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ret_val = func(args) print "return value %s" % ret_val print "exiting %s" % (func_nam...


parameters - Python Newbie: Returning Multiple Int/String Results in Python

I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at leas...


Print out list of function parameters in Python

Is there a way to print out a function's parameter list? For example: def func(a, b, c): pass print_func_parametes(func) Which will produce something like: ["a", "b", "c"]


python - How to create a decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirectin...


python - Scope of lambda functions and their parameters?

This question already has answers here:


sql - How do you make the Python Msqldb module use ? in stead of %s for query parameters?

MySqlDb is a fantastic Python module -- but one part is incredibly annoying. Query parameters look like this cursor.execute("select * from Books where isbn=%s", (isbn,)) whereas everywhere else in the known universe (oracle, sqlserver, access, sybase...) they look like this cursor.execute("select * from Books where isbn=?", (isbn,)) This means that if you ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top