Saturday, May 16, 2015

for loop error with WLST python

Error in WLST python script for server status

 

Well, this post is for people like me who do lot of silly mistakes. Especially when we try to jump off a topic in pursuit of learning another.

 

I was in process of writing script to check the status of servers in my weblogic domain using WLST & python. While I was able to check status for each server by using separate command, the for loop would always result in error as described further.

 

Let’s go through the intended steps:

 

1.       Start WLST

2.       Connect to domain

3.       List and server and return the map into a map variable

4.       Run through a for loop, iteration over the server list obtained by return map

a.       Check status of each server in the variable

 

Now let’s directly jump to step 3

wls:/mazdapoc_domain/serverConfig> sList=ls('Servers',returnMap='true')

dr--   AdminServer

dr--   ess_server1

dr--   odi_server1

dr--   osb_server1

dr--   soa_server1

 

Now step 4, which gives error with iteration over “for” loop

wls:/mazdapoc_domain/serverConfig> for i in sList:

...state(i,'Server')

Traceback (innermost last):

  (no code object) at line 0

  File "<console>", line 2

        state(i,'Server')

        ^

SyntaxError: invalid syntax

 

While the single line commands work just fine

wls:/mazdapoc_domain/serverConfig> state(sList[0])

Current state of "AdminServer" : RUNNING

wls:/mazdapoc_domain/serverConfig> state(sList[1])

Current state of "ess_server1" : SHUTDOWN

wls:/mazdapoc_domain/serverConfig> state(sList[2])

Current state of "odi_server1" : RUNNING

wls:/mazdapoc_domain/serverConfig> state(sList[3])

Current state of "osb_server1" : RUNNING

wls:/mazdapoc_domain/serverConfig> state(sList[4])

Current state of "soa_server1" : RUNNING

 

Solution… or so!

Well, the cause of this error was a missing space after the first statement for initializing ‘for’ loop-

wls:/mazdapoc_domain/serverConfig> for i in sList:

...  print i

...

AdminServer

ess_server1

odi_server1

osb_server1

soa_server1

 

wls:/mazdapoc_domain/serverConfig> for i in sList:

...  state(i,'Server')

...

Current state of "AdminServer" : RUNNING

Current state of "ess_server1" : SHUTDOWN

Current state of "odi_server1" : RUNNING

Current state of "osb_server1" : RUNNING

Current state of "soa_server1" : RUNNING

 

As you can see in the code snipped above, providing a space in the beginning of the line after the ‘for’ loop initialization gives the required output. This is becuase the python language enforces indentation for loops. Now I know!!