2015-07-01 44 views
1

我想通過一個字符串部分到它下面的python函數 我不明白爲什麼我看到這個錯誤。我對這一點的理解是,它沒有得到一個字符串,在預期的地方。我試過鑄造,但那也不行。我怎樣才能解決這個問題或獲得更多的調試信息?更好的調試:期望一個字符緩衝對象

section = str('[log]') 
some_var = 'filename =' 

edit_ini('./bench_config.ini', section, some_var, 'logs/ops_log_1') 

功能導致錯誤

def edit_ini(filename, section, some_var, value): 

    section = False 

    flist = open(filename, 'r').readlines() 

    f = open(filename+'test', 'w') 

    for line in flist: 
      line = str(line) 
      print line 
      if line.startswith(section): 
        section = True 
        if(section == True): 
          if(line.startswith(some_var)): 
            modified = "%s = $s", variable, value 
            print >> f, modified 
          section = False 
      else: 
        print >> f, line 
    f.close() 

但是我看到的錯誤:

Traceback (most recent call last): 
    File "bench.py", line 89, in <module> 
    edit_ini('./config.ini', section, some_var, 'logs/log_1') 
    File "bench.py", line 68, in edit_ini 
    if line.startswith(section): 
TypeError: expected a character buffer object 

回答

0

您覆蓋傳入sectionsection=False。錯誤是因爲你不能撥打string.startswith(False)

調試python的一種方法是使用pdb。這會幫助你在這裏找到你的問題。你應該閱讀規範,但是這裏有關於如何使用pdb的快速指南。

import pdb 
# your code ... 
pdb.set_trace() # put this right before line.startswith(section) 

然後當你運行你的代碼時,你會在失敗之前執行到最後。然後你可以在pdb中打印section,看到它是False,然後試圖找出它爲什麼是False

相關問題