From: likang Date: Wed, 25 Jun 2014 07:31:17 +0000 (+0800) Subject: Make options.parse_config_file supporting custom encoding X-Git-Tag: v4.1.0b1~140^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=58323f062473aa0d6c1f7a75bbc6fceb07cfa996;p=thirdparty%2Ftornado.git Make options.parse_config_file supporting custom encoding --- diff --git a/tornado/options.py b/tornado/options.py index fa9c269ea..fd97f31f3 100644 --- a/tornado/options.py +++ b/tornado/options.py @@ -265,7 +265,7 @@ class OptionParser(object): return remaining - def parse_config_file(self, path, final=True): + def parse_config_file(self, path, final=True, encoding=None): """Parses and loads the Python config file at the given path. If ``final`` is ``False``, parse callbacks will not be run. @@ -273,8 +273,14 @@ class OptionParser(object): from multiple sources. """ config = {} - with open(path) as f: - exec_in(f.read(), config, config) + try: + # python 3 + with open(path, encoding=encoding) as f: + exec_in(f.read(), config, config) + except TypeError: + # python 2 + with open(path) as f: + exec_in(f.read(), config, config) for name in config: if name in self._options: self._options[name].set(config[name]) diff --git a/tornado/test/options_test.cfg b/tornado/test/options_test.cfg index 172714616..09a630600 100644 --- a/tornado/test/options_test.cfg +++ b/tornado/test/options_test.cfg @@ -1,2 +1,3 @@ port=443 -port=443 \ No newline at end of file +port=443 +username='李康' \ No newline at end of file diff --git a/tornado/test/options_test.py b/tornado/test/options_test.py index 2279c4b3f..82c4495fd 100644 --- a/tornado/test/options_test.py +++ b/tornado/test/options_test.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, with_statement import datetime @@ -32,9 +33,12 @@ class OptionsTest(unittest.TestCase): def test_parse_config_file(self): options = OptionParser() options.define("port", default=80) - options.parse_config_file(os.path.join(os.path.dirname(__file__), - "options_test.cfg")) + options.define("username", default='foo') + cfg_path = os.path.join(os.path.dirname(__file__), "options_test.cfg") + options.parse_config_file(cfg_path, encoding="utf-8") + self.assertEquals(options.port, 443) + self.assertEqual(options.username, "李康") def test_parse_callbacks(self): options = OptionParser()