Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Option Parser: Boolean flag with optional parameters

I'm using optparse.OptionParser to manage arguments for some scripts, and something I was wondering / would like to do is have boolean flags (i.e action=store_true) that can also accept a parameter.

To put this into context, I've got a application that can use as many GPU/Processors as it finds on the machine. For a variety of reasons sometimes you want to limit the number of devices it uses, and instead of further cluttering the command line, I'd like to be able to:

script -c -g

meaning use all you can of all cpus and gpus, and

script -c 2 -g 3

meaning limit the script execution to 2 CPUs and 3 GPUs.

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

like image 802
Bolster Avatar asked May 11 '11 10:05

Bolster


1 Answers

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

Things get hairy when you want an option to take a variable number of arguments. For this case, you must write a callback, as optparse doesn’t provide any built-in capabilities for it.

like image 156
Eli Bendersky Avatar answered Oct 11 '22 13:10

Eli Bendersky