tornadoweb / tornado

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
http://www.tornadoweb.org/
Apache License 2.0
21.71k stars 5.5k forks source link

unable to use __file__ to get the project base_dir from the tornado.options.parse_config_file. #1666

Closed hackrole closed 8 years ago

hackrole commented 8 years ago

I use tornado.options to define a few options and parse from both the file and cmdline. the problem is that I want to get the base_dir by use os.path.realpath(file). which will raise Exception.

how can I got out of this. this code was like below.

# options.py
# -*- coding: utf-8 -*-

from tornado.options import options

def define_options(option_parser):
    """定义配置"""
    def config_callback(path):
        option_parser.parse_config_file(path, final=False)

    option_parser.define('config', type=str, help="config file path",
                         callback=config_callback, group="config file")
    option_parser.define('file_path', type=str, help="path",
                         group="config")
    return option_parser

if __name__ == "__main__":
    opts = define_options(options)
    opts.parse_command_line(['options.py', '--config=config.py'])
    print opts.host, opts.port

# config.py
# -*- coding: utf-8 -*-

from os import path

# this will raise
base_path = path.dirname(path.realpath(__file__))

file_path = path.join(base_path, 'hello.ini')

while I run python options.py, it will raise Error. the error msg was beow.

$ python options.py
Traceback (most recent call last):
  File "options.py", line 19, in <module>
    opts.parse_command_line(['options.py', '--config=config.py'])
  File "/home/daipeng/.virtualenvs/logagent_env/local/lib/python2.7/site-packages/tornado/options.py", line 286, in parse_command_line
    option.parse(value)
  File "/home/daipeng/.virtualenvs/logagent_env/local/lib/python2.7/site-packages/tornado/options.py", line 448, in parse
    self.callback(self._value)
  File "options.py", line 9, in config_callback
    option_parser.parse_config_file(path, final=False)
  File "/home/daipeng/.virtualenvs/logagent_env/local/lib/python2.7/site-packages/tornado/options.py", line 306, in parse_config_file
    exec_in(native_str(f.read()), config, config)
  File "<string>", line 10, in exec_in
  File "<string>", line 7, in <module>
NameError: name '__file__' is not defined
bdarnell commented 8 years ago

Thanks for the report; I've added support for __file__ to the config file.