[Mono-list] Command line processing tool in C#

Jonathan Pryor jonpryor@vt.edu
Wed, 07 Apr 2004 20:59:32 -0400

Content-Type: text/plain
Content-Transfer-Encoding: 7bit


On Wed, 2004-04-07 at 15:15, Thomas R. Corbin wrote:
> I've been using this tool in python:
> http://www.python.org/doc/2.3/lib/module-optparse.html
> And wondered if there was a similar tool in C# or for mono.

There's a better one (in my obviously biased opinion): Mono.GetOptions.

See the attached file for an example.  It's unique in the option-parsing
world (AFAIK) in that it uses attributes to specify the help text,
short, and long flags that are interpreted.

The one thing I can't figure out is how to specify "verbosity levels",
where "-v -v -v" would be a valid set of command line arguments...

 - Jon

Content-Disposition: attachment; filename=go.cs
Content-Type: text/plain; name=go.cs; charset=UTF-8
Content-Transfer-Encoding: 7bit

// Mono.GetOptions demo
// Compile with: mcs -r:Mono.GetOptions go.cs

using System;
using System.Reflection;
using Mono.GetOptions;

// Attributes visible in "<program-name/> --help"
[assembly: AssemblyTitle ("go.exe")]
[assembly: AssemblyVersion ("1.0.*")]
[assembly: AssemblyDescription ("Mono.GetOptions Sample Program")]
[assembly: AssemblyCopyright ("Public Domain")]
// This is text that goes after "<program-name/> [options]" in help output.
[assembly: Mono.UsageComplement ("")]

// Attributes visible in "<program-name/> -V"
[assembly: Mono.About ("Insert About Text Here.")]
[assembly: Mono.Author ("Jonathan Pryor")]

class SampleOptions : Options
	// Long option is the variable name ("--file"), short option is -f
	[Option ("Write report to FILE", 'f')]
	public string file;

	// Long option is the variable name ("--quiet"), short option is -q
	[Option ("don't print status messages to stdout", 'q')]
	public bool quiet;

	// Long option is as specified ("--use-int"), no short option
	[Option ("Sample int option", "use-int")]
	public int use_int;

	public SampleOptions ()
		base.ParsingMode = OptionsParsingMode.Both;

class TestApp
	public static void Main (string[] args)
		SampleOptions options = new SampleOptions ();
		options.ProcessArgs (args);

		Console.WriteLine ("Specified Program Options:");
		Console.WriteLine ("\t           file: {0}", options.file);
		Console.WriteLine ("\t          quiet: {0}", options.quiet);
		Console.WriteLine ("\t        use_int: {0}", options.use_int);

		Console.WriteLine ("Remaining Program Options:");
		foreach (string s in options.RemainingArguments) {
			Console.WriteLine ("\t{0}", s);