Archive for July, 2010

Python: AttributeError: ‘getopt’ module has no attribute ‘GetoptError’

Wednesday, July 28th, 2010

So I was figuring out how to parse command line arguments with python and using the getopt module with the following code


#!/usr/bin/env python
import sys
import getopt

def main(argv):
   infile = "some.xml"
   try:
      opts,args = getopt.getopt(argv,"hi:d",["help","infile="]
   except getopt.GetoptError:
      usage()
      sys.exit(2)

if __name__ == "__main__":
    main(sys.argv[1:])

And I was getting the following error:

AttributeError: ‘getopt’ module has no attribute ‘GetoptError’

So my first problem was that I had named my script getopt.py and after renaming the script, I got the same error. Well you now need to remove the getopt.pyc file that was generated from your earlier running of the poorly named script.

How to address perl arguments

Wednesday, July 28th, 2010

If you are using perl, you may find it necessary to take some command line arguments to your scripts.  When that time comes, there is a very handy variable ARGV that contains the passed in arguments.

To get the total number of arguments passed into the script you will need to use the following:

$totcommandargs = #$ARGV + 1

is equal to the number of arguments passed in to the Perl script.

Note: you need to add one to the count to get the correct number of variables.

To address the variables you use the following to address the first argument: $ARGV[0]

will address the first argument

Since arrays are addressed by n-1, to get the first element you use 0 {zero}, for the second 1, for the third {2}, and so on.

$0 will give the name of the currently executing script.


#!/usr/bin/perl

$argcount =  $#ARGV +1;
print "The script $0 has $argcount argumentsn";

for( $i = 0; $i < $argcount;$i++)
{
print $ARGV[$i] . "n";
}

Bash: Command line parser for Multiple arguments to bash

Tuesday, July 20th, 2010

I regularly have to write scripts into different environments and when I am wrapping a build system, I typically use a Bash script to do it. I often have to pass a set of arguments to the underlying commands in my scripts as well. I have found that the %* argument is the easiest way to take those arguments.

The %* takes the arguements and passes them along. The %1, %2, %3…and so on are the individual arguments but unless you have a fixed amount of arguments, then you will need to process a variable amount of arguments.

while [ $#  -gt 1 ]
do
  case "$1" in
    -a)
      ANALYZE=1
      ;;
    *)
     echo "Invalid option"
     ;;
   esac
   shift
done