Python Option Parser: boolean flag with optional parameters

I use optparse.OptionParser to manage the arguments for some scripts, and something that I was interested / would like to do is to have boolean flags (i.e. action=store_true ) that can also take a parameter.

To include this in context, I have an application that can use as many GPUs / processors as it finds on the machine. For various reasons, sometimes you want to limit the number of devices that it uses, and instead of further cluttering the command line, I would like to be able to:

 script -c -g 

means using everything you can from all cpus and gpus, and

 script -c 2 -g 3 

means restricting script execution to 2 processors and 3 GPUs.

After reading the optparse documentation, I'm no wiser. Oh great SO gurus! Lend me your wisdom!

+6
source share
1 answer

You can use the callback action to implement this quite easily. In particular, Example 6 in the documentation for the OptionParser callback OptionParser discusses a variable number of arguments. Here is a quote from this example:

Things get hairy when you want the ability to accept a variable number of arguments. In this case, you should write a callback, because optparse doesnt provide any built-in capabilities for it.

+1
source

Source: https://habr.com/ru/post/887813/


All Articles