It is easy to manage command line input for one or two parameters by relying on the order. You can remember the order, document the order, or add some simple help message to your program. This works fine for a few items. Dealing with the ordering becomes difficult as the number of parameters grows. I decided to try using YAML to avoid the complexity of parsing the command line.
The following is a simple example of using YAML in Ruby instead of command line arguments.
The data file:
key: data project: name: MyFirst repo: svn://localhost/svn/myfirst
Rather simple data, but data nonetheless. Assuming the data file is named data.yml, I’ll experiment with it in Ruby’s interactive shell:
>> require 'yaml' => true >> input = YAML.load_file('data.yml') => {"project"=>{"name"=>"MyFirst", "location"=>"svn://localhost/svn/myfirst"}, "key"=>"data"} >> puts "Received key value: #{input['key']}" Received key value: data => nil
The example loads the file in to the ‘input’ hash. Next we use the hash key ‘key’ to get its value ‘data’. The ‘project’ collection from our input is another hash. We can access it:
> project = input["project"] => {"name"=>"MyFirst", "location"=>"svn://localhost/svn/myfirst"} >> project.each { | k, y| puts "#{k} : #{y}" } name : MyFirst location : svn://localhost/svn/myfirst => {"name"=>"MyFirst", "location"=>"svn://localhost/svn/myfirst"}
Putting the example together as a script that reads the data file from the command line:
#!/usr/bin/env ruby require 'yaml' filename = ARGV[0] input = YAML.load_file(filename) puts "Key value: #{input['key']}" # grab the 'project' hash project = input["project"] # output the key : value pairs from the hash project.each { | key, value| puts "#{key} : #{value}" }
The simple script outputs:
$ ./simpleyaml.rb data.yml Key value: data name : MyFirst location : svn://localhost/svn/myfirst
Here is the same script in Python:
#!/usr/bin/env python import yaml import sys f = open(sys.argv[1]) input = yaml.load(f) print "Key value: " + input["key"] project = input["project"] for key, value in project.items(): print key + " : " + value