]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Make options.parse_config_file supporting custom encoding
authorlikang <i@likang.me>
Wed, 25 Jun 2014 07:31:17 +0000 (15:31 +0800)
committerlikang <i@likang.me>
Wed, 25 Jun 2014 08:12:34 +0000 (16:12 +0800)
tornado/options.py
tornado/test/options_test.cfg
tornado/test/options_test.py

index fa9c269ea7d093701af328d8f93a25812d56edb8..fd97f31f3ffbb617290e6677daf0cd580d4589d7 100644 (file)
@@ -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])
index 172714616a7e40ca4695a08c13c9b4c4b17267c5..09a63060063b0f896a315abdaafc5a04759f036c 100644 (file)
@@ -1,2 +1,3 @@
 port=443
-port=443
\ No newline at end of file
+port=443
+username='李康'
\ No newline at end of file
index 2279c4b3f13cb3bc45e561d124cdebb30d7da858..82c4495fd4d3ec74b9edcec4fa18d4a620acbbb1 100644 (file)
@@ -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()