Pages

Tuesday, November 19, 2013

Storing Shell Command Output using Python

In my development setup I need to reserve lot of corporate systems/resources to carry out the scenario testing. Once the development is frozen, I used to manually release all the reserved resources. If a development cycle for a particular release goes beyond 3 months, the number of entries which needs to be released would be more than 50(sometimes 100+). Its a big pain for me when we all were in party mode. So the simple way to automate this repeated less interesting manual task.

The manual steps which I followed earlier is given below.


(1) Run a shell command which will display the list of reserved resources with descriptions.

# mycommand -x -u siva

entry1         description1
entry2         description2
entry3         description3
entry4         description4

entryN         descriptionN
(2) Run another shell command multiple times which releases the given resource.
# commandx -d entry1  
# commandx -d entry2

# commandx -d entryN

Note: entry* is not allowed in the commandx. So I have to run this command individually for each entry.

My python script requirement is very simple.
  • Store the output of mycommand in a file
  • Read the entries one by one (first part of each line from the file)
  • Run a commandx with the above  entry

Initially I was trying with the following snippet. But it was very hard to provide multiple options and write to a file.

from subprocess import call
call(["command", "option1"]) 

Finally, I used commands to module to create a python script in a simpler way.

import commandsf = open("entries.txt", "w")
f.write(commands.getstatusoutput('mycommand -x -u siva')[1])
f.close()
f = open("entries.txt")
for line in f.readlines():
    print commands.getstatusoutput('commandx -d '+ line.split()[0])
f.close()

No comments:

Post a Comment