[英]Python to print previous line if an condition met in current line
`I creating health check script for the check the oracle data-gaurd status `我创建运行状况检查脚本以检查oracle数据域状态
The datagaurd status output will be like 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
or it will also like 否则它也会喜欢
<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
so my requirement is to print the previous line when error "ORA" occurs means which database is having the ORA- Error 所以我的要求是在发生错误“ ORA”时打印上一行,这意味着哪个数据库存在ORA-错误
The output is small I can keep all the lines is buffer but the no:of lines is not constant. 输出很小,我可以保留所有行为缓冲区,但是no:of的行不是恒定的。 So is there any procedure to get the line number where ORA will be there and so print the previous line This is the code I have tried 那么是否有任何程序来获取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
When iterating over the lines, can't you just keep the previous line in each iteration? 遍历各行时,是否不能仅在每次迭代中保留前一行?
# 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
If you can get the error as a string, you can use string.count("\\n")
to get the count of newline characters. 如果可以字符串形式获取错误,则可以使用string.count("\\n")
来获取换行符的计数。 You can also use string.split("\\n")
which returns an array of lines of your string. 您还可以使用string.split("\\n")
返回字符串的行数组。 array[-1]
is the last line in the array, and array[-2]
is the pre-last one. array[-1]
是array[-1]
中的最后一行,而array[-2]
是前最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.