2016-08-01 90 views
0

我有一個文件名爲mcelog.conf,我正在讀取我的代碼中的這個文件。該文件的內容是從python的文件中讀取一行

no-syslog = yes # (or no to disable) 
logfile = /tmp/logfile 

計劃將讀取mcelog.conf文件,將檢查no-syslog標籤,如果no-syslog = yes然後程序必須檢查標籤logfile和將讀取logfile標籤。任何人都可以讓我知道我怎麼可以得到價值/tmp/logfile

with open('/etc/mcelog/mcelog.conf', 'r+') as fp: 
    for line in fp: 
     if re.search("no-syslog =", line) and re.search("= no", line): 
      memoryErrors = readLogFile("/var/log/messages") 
      mcelogPathFound = true 
      break 
     elif re.search("no-syslog =", line) and re.search("= yes", line): 
      continue 
     elif re.search("logfile =", line): 
      memoryErrors = readLogFile(line) # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed 
      mcelogPathFound = true 
      break 
fp.close() 
+0

您是否嘗試過正則表達式組?甚至在等號上分裂,並且基本上創造了一個鍵值的字典? –

+0

不,我還沒有嘗試正則表達式組,如果我打算用'='符號拆分每一行,那麼有一個機會,如果文件中存在一些註釋,則會出現異常。 @ cricket-007 –

+0

爲什麼?你已經評論了兩個答案,告訴你同樣的事情 –

回答

1

更改代碼:

with open('/etc/mcelog/mcelog.conf', 'r+') as fp: 
    for line in fp: 
     if re.search("no-syslog =", line) and re.search("= no", line): 
      memoryErrors = readLogFile("/var/log/messages") 
      mcelogPathFound = true 
      break 
     elif re.search("no-syslog =", line) and re.search("= yes", line): 
      continue 
     elif re.search("logfile =", line): 
      emoryErrors = readLogFile(line.split("=")[1].strip()) # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed 
      mcelogPathFound = true 
      break 
fp.close() 

這是因爲你想只讀行,而整個事情的一部分,所以我只是把它分解了由「=」號,然後剝去它以除去

+0

當我嘗試'emoryErrors = readLogFile(line).split(「=」)[1] .strip()'仍然readLogFile函數傳遞相同的參數「logfile =/tmp/logfile」。但當我傳遞像'emoryErrors = readLogFile(line.split(「=」)[1] .strip())'那麼它的工作正常。 @ gaurav-dhama –

+0

是我的錯誤。修改了我的答案以反映相同。儘管如此,我希望你明白了。 –

+0

是的,這個主意和它的工作很好。謝謝@ gaurav-dhama –

2

你只能分割線,以獲得您想要的值:

line.split(' = ')[1] 

但是,您可能想看看的文檔configparser module

+0

當我嘗試了'emoryErrors = readLogFile(line.split(「=」)[1] .strip())',那麼它的好用。謝謝@icart –

1

我喜歡的configparser模塊的建議任何空白,所以這裏就是一個很好的示例(Python 3)

對於給定的輸入,它將輸出reading /var/log/messages

import configparser, itertools 
config = configparser.ConfigParser() 
filename = "/tmp/mcelog.conf" 

def readLogFile(filename): 
    if filename: 
     print("reading", filename) 
    else: 
     raise ValueError("unable to read file") 

section = 'global' 
with open(filename) as fp: 
    config.read_file(itertools.chain(['[{}]'.format(section)], fp), source = filename) 

no_syslog = config[section]['no-syslog'] 
if no_syslog == 'yes': 
    logfile = "/var/log/messages" 
elif no_syslog == 'no': 
    logfile = config[section]['logfile'] 

if logfile: 
    mcelogPathFound = True 

memoryErrors = readLogFile(logfile)