Archive for July 28th, 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";
}