Tag Archive


3D 3dprinting android ant BigData bitcoin Browsers C/C++ cryptocurrency CSS dd ddrescue dogecoin DOS editors find Games Git hadoop html html5 Java Linux litecoin node perl Postgres Programming Python scripting Shell SQL Swing TOTK Utilities utilization vi Video Web Web Design Wifi Windows Wordpress XML Zelda

Python: Handle Command line arguments with Optparse

Here is my basic script for handling command line arguments in Python(pre version 2.7 when optparse
was deprecated). The optparse library is very useful in not only handling the command line
arguments, but setting up your help menu as well.

You will need to create an OptionParser and the usage argument lets you print the usage statement
for the script. Then you can add options, add groups for options or collect the left over
parameters as a secondary command or list of files. I use this method often as I create scripts
that help automate build processes.

#!/usr/bin/python

import sys, optparse

# This creates an OptionParser object with the usage string.
op = optparse.OptionParser(usage=" %prog [options]")
# This will add an option -m or --mode which takes sets the mode variable as
# True or False
op.add_option("-m","--mode",help="Specify the mode for the command", 
            action="store_true", dest="mode",default=False)
# This parses the options and places the selected options above in the _options
# object and the rest in arguments.
_options,arguments = op.parse_args()

# Checks if no arguments are passed and if so, runs the print_help method of 
# the OptionParser object
if len(sys.argv) == 1:
    op.print_help()

# This was just to show what happened when you did or didn't pass the
# --mode argument.
if  _options.mode:
    print "Mode is on"
else:
    print "Mode is off"

This method is currently deprecated as of version 2.7. I will write a follow-up post that uses
the newer argparse routine to highlight any differences.

DOS: Capture return values from commands

When I am writing build automation scripts, there are times that I have to insure that the previous command completed
with no errors. I have found that ERRORLEVEL gets filled in with the return value from a command.

dir %1

if (%ERRORLEVEL%) == (0) echo Found File: %1
if (%ERRORLEVEL%) == (1) echo Missing File: %1

So if you save the previous in a file and run the command with one (1) argument, it will display the output of the dir command
but also print either “Found file: ” or “Missing File: “.

Python: error when using the input() function

I was writing a basic guessing game and when I tried to take user input I was
getting the following:

Code:

guess = input()
d

Error:

Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'd' is not defined

The problem is actually with the version of Python that I was using. If you
are using Python 2.x, you need to use the raw_input() function. And with 3.x
you can use the input() function.

Python: if/else Statements

There comes a time when you are writing a program and you need to branch based on input to a program.
This is the format of the if/else statement in Python.

if <some true/false statement> :
  <some statements that run if the if statement is true>
else:
  <some other statements that run if the if statement are false>  

There may be times when you have more than one value set to test against. In that case you can write a many if/else
statements but you can chain the if/else statements with an elif. So the chain becomes if/elif/else.

if x < 5:
  <some statements that run if the if statement is true>
elif x > 5 and x < 10:
  <some statements that run if the elif statement is true>
else:
  <if none of the if checks are true, run the statements in the else case.>

Python: Allow for empty if else blocks

I was toying with a prime number finder and was creating a set of if/else statements for a horribly failed attempt
and wanted to skip to the next number on any of the if statements that were true. I didn’t want to put an empty print
statement as that would disrupt the output I was expecting from the program. I found the pass statement.
Here is an example from my not very successful attempt at finding primes:

if inp > 2 and inp % 2 == 0:
  pass
elif inp > 3 and inp % 3 == 0:
  pass
elif inp > 7 and inp % 7 == 0:
  pass
elif inp > 9 and inp % 9 == 0:
  pass
else:
  print inp, " is a prime"

Yes, this does not accurately find the primes, but it would skip any number that is divisible by 2,3,5,7, or 9. And
anything that does not match this will be listed as a prime, this is incorrect and would be made to add new elif
statements as each prime was found.

Perl: Format date strings

The other day I had a requirement to fill in a date value while creating an entity in ClearQuest. The field that was required was a date and was formatted as “mm/dd/yyyy hh:MM::SS AM|PM”. I used the localtime function to return the date and used sprintf to format the date to the proper output.
The reason I used sprintf was that for hours, months and days less 10 the output was 1 digit instead of two and the input was not allowed. The %02d states that the digits used will be a minumum of 2 in this case.

Here is the sample program I wrote to test the expected output:

 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;

# formatted just by concatenating output
my $datestring = $mon . "/" . $mday . "/" . $year . "  " . $hour . ":" . $min.
":" . $sec  ;

# formatted using sprintf to ensure proper digit counts are output
my $datestring2 = sprintf("%02d/%02d/%04d %d:%02d:%02d %s",$mon,$mday,1900 +$yea
r,$hour,$min,$sec, $hour >= 12? "PM" : "AM");

 print $datestring;
  print $datestring2;

DOS: Check for empty environment variable

I was writing a batch file the other day and needed to change the argumets to a command based on if the user had specified his password on the command line.

SET PASS=somepassword
: or
:SET PASS=
if x%PASS%= X (
  SET PASSARG=--password somepassword
) else
(
  SET PASSARG=
)

commandtorun %PASSARG%

Now if the user comments out his password, the script will make the PASSARG environment variable be empty or if they set a password the passarg variable will be filled in.

Linux:Script to use find to search contents of files

I use find and grep quite a bit. I found that I was regularly searching for strings in file and was typing commands like:

find . -exec grep "somestring" {} ; --print

This find command will search from the current directory and for each file will run grep on it and if it finds a matching string, it will print the string and then the filename. So I took this and moved it into a script.

#!/bin/sh

if [ $# -lt 1 ]; then
  echo 1>&2 Usage: $0 ""
  exit 127
fi
icase=
search=

while [ $# -ge 1 ]; do
  case $1 in
     -i) icase=$1;;
      *) search=$1 ;;
  esac
  shift
done

find . -type f -print0 | xargs -0 grep $icase $search

This allows me to run a command such as

ffind -i Super

This command will search all file names starting from the current directory and recurse directories and the “-i” will tell it to ignore case.

Perl: Open and read file line by line

I regularly have to process Comma Seperated Value or CSV files, usually for user lists. So the following perl code is a framework for processing a file line by line.

#!/usr/bin/perl
use strict;
my $line;

open(FILEIN, "filename.txt");

while(<FILEIN>)
{
  chomp();
  $line = $_;
  # Process $line for data
  # Example seperating line by commas: 
  my ($username,$firstname,$lastname,$email) = split(/,/,$line);
}

close(FILEIN);

Perl: Hashes

Here are some basics about Perl hashes that can be helpful to be used when an you need to associate a label with some value such as for names and telephone numbers or account numbers with amounts owed.

Create a hash variable.

my %hashvar;

Create a hash reference

my $refhash = {};

Add a value to a hash variable.

$hashvar{'somekey'} = 'someval';

Add a value to a hash reference.

$hashref->{'somekey'} = 'someotherval';

Access a value in a hash.

print $hashvar{'somekey'};

Access a value in a hash reference.

print $hashref->{'somekey}';

Access all Keys in a hash variable.
foreach my $k (keys(%hashvar))
{
print $hashvar{$k};
}

Access all Keys in a hash reference.

foreach my $k (keys(%$hashref))
{
  print $k . "n";
}

Access all Keys and values in a hash.

while (my ($key,$value) = each %hashvar)
{
  print "Key: " . $key . " has value:" . $value . "n";
}

Access all Keys and values in a hash.

while (my ($key,$value) = each %$refhash)
{
  print "Key: " . $key . " has value:" . $value . "n";
}

Assigning multiple values to a hash

%hasvar = (
  'test2' => 'myval',
  'test3' => 'myval3'
);

Note: This will clear the existing hash.

Delete a value from a hash

delete $hashvar{'key1'};

Delete a value from a hash reference.

delete $hashref->{'key1'};