Python如果在当前行

时间:2016-02-25 06:51:07

标签: python arrays

`我创建了用于检查oracle data-gaurd状态的健康检查脚本

datagaurd状态输出将类似于

<Database_Name 1> - Primary database
   Warning: ORA-16817: unsynchronized fast-start failover configuration
 <Database_Name 2> - (*) Physical standby database
   Warning: ORA-16817: unsynchronized fast-start failover configuration

或者它也会喜欢

<Database_Name 1> - Primary database
   Warning: ORA-16817: unsynchronized fast-start failover configuration
 <Database_Name 2> - (*) Physical standby database
   Warning: ORA-16817: unsynchronized fast-start failover configuration

所以我的要求是在出现错误“ORA”时打印上一行意味着哪个数据库具有ORA-错误

输出很小我可以保持所有行都是缓冲区,但是no:of lines不是常量。那么是否有任何程序可以获得ORA所在的行号,从而打印上一行 这是我试过的代码

#!/usr/bin/env python import sys, os, time, threading, subprocess,datetime,re command = 'su - emadba -c \'dgmgrl -silent sys/password@emadb "show configuration"\'' dgstatus = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True) output = dgstatus.communicate()[0].strip().split("\n") prev = "" print prev for x in output: prev = x

2 个答案:

答案 0 :(得分:1)

当迭代这些行时,你不能在每次迭代中保留上一行吗?

# Holds the previous line
prev_line = None
for line in open(<something>, 'r'):
    if is_ora_line(line) and prev_line is not None:
        do_something_with_database_line(prev_line)
    # Remember now the current line as the previous line
    prev_line = line

答案 1 :(得分:1)

如果您可以将错误作为字符串获取,则可以使用string.count("\n")来获取换行符的计数。您还可以使用string.split("\n")返回字符串的行数组。 array[-1]是数组中的最后一行,array[-2]是前一行。