Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Sunday, 3 February 2013

Reading environment variables in python

February 03, 2013 Posted by Dinesh 5 comments

The os module contains an interface to operating system-specific functions. this module can be used to access environment variables. 
We can go with os.environ to get the value of environment variable.

import os
print os.environ['HOME']

but there is a catch, this method will raise KeyError variable does not exist 

>>> print os.environ['HOME_NOT_EXIST']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'HOME_NOT_EXIST'

So it is better to go with os.getenv. this return None if key/environment variable does not exist. and if we require we can return default values too.

print os.getenv('KEY')    #returns None if KEY doesn't exist
print os.getenv('KEY', 0) #will return 0 if KEY doesn't exist 

All about variables/parameters in shell

February 03, 2013 Posted by Dinesh , , No comments


Stripping Variable Strings By length:


Syntax: ${parameter:starting_index:number_of_chars}

${variable:3}      # foobar becomes bar
${variable:3:2}   # foobar becomes ba
${variable: -4}   # foobar becomes obar


Upper and lower case :


y="this IS small"
echo "${y^^}"
THIS IS SMALL

y="THIS is BIG"
echo "${y,,}"
 this is big

Removing a Part:


name=${var#removepat}
This will remove 'removepatt' from variable(begining) var and assign to name

name=${var%removepat}
can use % to remove the pattern at the end. useful when one wish to remove trailing / from path names

##   Deletes longest match of $removepat from front of $var.
%%  Deletes longest match of $removepat from back of $var.


Here is the example which will tokenize positional parameters based on =

tmp=${1}
parameter=${tmp%%=*}     # Extract name.
value=${tmp##*=}               # Extract value.

if $1 is a=1, then
parameter=a     #strip from back till = ; so =* will be removed    
value=1            # strip from front till = ; so *= will be removed

Substring Replacement:


${string/substring/replacement}
Replace first match of $substring with $replacement.${string//substring/replacement}Replace all matches of $substring with $replacement.
string=abcABC123ABCabc
echo ${string/abc/xyz}                  # xyzABC123ABCabc
echo ${string//abc/xyz}                 # xyzABC123ABCxyz

Following will simply delete the pattern from string.
string=abcABC123ABCabc
echo ${string/abc/}            # ABC123ABCabc
echo ${string//abc/}           # ABC123ABC


Get Length:

To calculate length of any variable in shell, # can be used.

a="ABCD"
${#a}
4

Calculate number of elements in array:

$ os=("linux" "solaris" "aix")
$ echo {#os[*]}
3
$ echo {#os[@]}
3

@ or * can be used to access all elaments of an array.
These native methods will be faster since we are not invoking any third party tools.

Note: without '(  )' result can't be treated as array.

AWK/CUT implementation (simplified) :


dinesh@ubuntu:~$ a="abc 123 qqq"
dinesh@ubuntu:~$ set -- $a
dinesh@ubuntu:~$ echo $1
abc
dinesh@ubuntu:~$ echo $2
123
dinesh@ubuntu:~$ echo $3
qqq
dinesh@ubuntu:~$