Database Reference
In-Depth Information
Listing 6-2. Use awk to parse the process detail
[oracle@server ]$ ps -ef | grep [t]nslsnr | awk '{print $8,$9,$10}'
/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr LISTENER -inherit
Listing 6-3 shows that Python would treat the output from the ps command as an object made up of pieces. The delimiter
used in the previous example is one or more spaces. We can parse the same command using Python instead of awk .
Listing 6-3. Use Python to parse the process detail
>>> psout = 'oracle 1723 1 0 16:21 ? 00:00:01
/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr LISTENER -inherit'
>>> type(psout)
<type 'str'>
>>> psoutlist = psout.split()
>>> type(psoutlist)
<type 'list'>
>>> psoutlist[7:]
['/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr', 'LISTENER', '-inherit']
>>> ' '.join(psoutlist[7:])
'/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr LISTENER -inherit'
>>> psoutstring = ' '.join(psoutlist[7:])
>>> psoutstring
'/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr LISTENER -inherit'
psoutlist = psout.split() breaks apart the string into a list made up of string elements based on a delimiter of
whitespace and assigns it to the psoutlist list object. psoutlist[7:] prints a subset of the psoutlist list object from
the eighth (remember that a list index starts at 0) to the final element. psoutstring = ' '.join(psoutlist[7:])
joins the subset of elements back into a string delimited by a single space and assigns it to the psoutstring string
object. What really makes Python shine is that this can all be done in one command, as shown in Listing 6-4.
Listing 6-4. Combine the commands from Listing 6-3 into a single command
>>> ' '.join('oracle 1723 1 0 16:21 ? 00:00:01
/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr LISTENER -inherit'.split()[7:])
'/u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr LISTENER -inherit'
Listing 6-3 populates the psout variable directly with the output from the ps command. The process of capturing
the output of the ps command could also be done directly from within Python, as shown in Listing 6-3a.
Listing 6-3a. Capture the ps command output using the Python subprocess module
>>> import subprocess
>>> mycommand = ['ps', '-ef']
>>> psoutput = subprocess.Popen(mycommand, stdout=subprocess.PIPE).communicate()[0].split('\n')
>>> for i in psoutput:
... if 'tnslsnr' in i:
... psout = i
Lists are a useful way of grouping strings and numbers together in Python, but sometimes a more complex object
is required. Sometimes an index of single elements is not enough and we need a way of grouping keys and values
together. This is especially true when working with EM CLI, where arrays are common and often complex. This is
where Python dictionary objects come in.
Search WWH ::




Custom Search