Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 code 模块来调试 Python 代码 #16

Open
WyattJia opened this issue May 12, 2017 · 0 comments
Open

使用 code 模块来调试 Python 代码 #16

WyattJia opened this issue May 12, 2017 · 0 comments
Labels

Comments

@WyattJia
Copy link
Owner

WyattJia commented May 12, 2017

以调试 flask 应用为例,我们先构建一个最小化的 flask 应用作为参考示例:

# hello.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

命令行输入 python hello.py , 我们就能在 http://localhost:5001 访问我们的 hello world 应用了。


但是今天我们要换一种方式来启动我们的应用。

首先我们在 hello.pyimport code, 然后把最后一行的 app.run() 改成 code.interact(local=locals()).
更改后的 hello.py 就变成下面这个样子:

# hello.py
import code
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    code.interact(local=locals())

接下来我们继续在命令行执行 python hello.py来运行程序。注意运行结果,Python 给了我们一个 带有入门文件环境的 REPL ! 这就是 Python 自带的 code 模块的神奇之处!
接下来我们在 REPL 中试试看 code 模块有没有 hello.py 中的内容引入进来:

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 12:54:16)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import pprint
>>> pprint.pprint(app.__dict__)
{'_before_request_lock': <thread.lock object at 0x101487a50>,
 '_blueprint_order': [],
 '_error_handlers': {},
 '_got_first_request': False,
 '_logger': None,
 '_static_folder': 'static',
 '_static_url_path': None,
 'after_request_funcs': {},
 'before_first_request_funcs': [],
 'before_request_funcs': {},
 'blueprints': {},
 'cli': <flask.cli.AppGroup object at 0x10310a710>,
 'config': <Config {'JSON_AS_ASCII': True, 'USE_X_SENDFILE': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_REFRESH_EACH_REQUEST': True, 'LOGGER_HANDLER_POLICY': 'always', 'LOGGER_NAME': '__main__', 'DEBUG': False, 'SECRET_KEY': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'MAX_CONTENT_LENGTH': None, 'APPLICATION_ROOT': None, 'SERVER_NAME': None, 'PREFERRED_URL_SCHEME': 'http', 'JSONIFY_PRETTYPRINT_REGULAR': True, 'TESTING': False, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'PROPAGATE_EXCEPTIONS': None, 'TEMPLATES_AUTO_RELOAD': None, 'TRAP_BAD_REQUEST_ERRORS': False, 'JSON_SORT_KEYS': True, 'JSONIFY_MIMETYPE': 'application/json', 'SESSION_COOKIE_HTTPONLY': True, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SESSION_COOKIE_SECURE': False, 'TRAP_HTTP_EXCEPTIONS': False}>,
 'error_handler_spec': {None: {}},
 'extensions': {},
 'import_name': '__main__',
 'instance_path': '/Users/Wells/Documents/blogic/instance',
 'name': 'hello',
 'root_path': '/Users/Wells/Documents/blogic',
 'shell_context_processors': [],
 'teardown_appcontext_funcs': [],
 'teardown_request_funcs': {},
 'template_context_processors': {None: [<function _default_template_ctx_processor at 0x1017c08c0>]},
 'template_folder': 'templates',
 'url_build_error_handlers': [],
 'url_default_functions': {},
 'url_map': Map([<Rule '/' (HEAD, OPTIONS, GET) -> hello>,
 <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>]),
 'url_value_preprocessors': {},
 'view_functions': {'hello': <function hello at 0x10310b1b8>,
                    'static': <bound method Flask.send_static_file of <Flask 'hello'>>}}

显然是引入进来了, 这样我们可以通过 REPL 调试代码,在某些场景(例如没有 IDE 的情况下)下会很适用。


相关链接:


以上。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant