Đây là những gì tôi đã sử dụng. Phương pháp extended_get
là những gì bạn cần - nó hỗ trợ các phần phân cấp.
import re
import io
import ConfigParser
class ZendConfigParser(ConfigParser.ConfigParser):
def extended_get(self, section, key):
if self.has_option(section, key):
return self.get(section, key)
else:
orig_section, parent_section = self._get_orig_section(section)
if orig_section != None:
if self.has_option(orig_section,key):
return self.get(orig_section,key)
else:
return self.extended_get(parent_section,key)
else:
return None
def _get_orig_section(self, zend_section):
orig_section = None
parent_section = None
for section in self.sections():
if re.search(r'^[ \t]*' + zend_section + '\\b', section) != None:
orig_section = section
#look for a parent section
match = re.match(r'\w+[ \t]*:[ \t]*(\w+)$', section)
if match != None:
parent_section = match.groups()[0]
break
return (orig_section, parent_section)
config = ZendConfigParser()
config.read(file)
print(config.extended_get('production', 'database.params.host'))
Cảm ơn thông tin. Thật không may điều này sẽ không làm việc cho tôi do yêu cầu kinh doanh của việc có một tệp chính sẽ được phân tích cú pháp bằng một số ngôn ngữ lập trình. Có vẻ như tôi sẽ cần phải thực hiện bản thân mình. – Maascamp
Maascamp: bạn đã thành công chưa? Tôi có cùng một tình huống ... – xvga
Có, tôi đã triển khai một yêu cầu đáp ứng các yêu cầu của tôi (kiểu Zend_Config_Ini) và chuyển đổi thành các kiểu gốc tự nhiên nếu có thể. Xem tại đây [https://bitbucket.org/maascamp/pyconfigini](https://bitbucket.org/maascamp/pyconfigini). Hy vọng nó giúp. – Maascamp