如何使用Python 3.x ast模块解析Python 2.x? [英] How to parse Python 2.x with Python 3.x ast module?

查看:240
本文介绍了如何使用Python 3.x ast模块解析Python 2.x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一个Sublime Text 3插件来解析Python代码并从中发布一些统计信息.

I recently wrote a Sublime Text 3 plugin that parses Python code and issues some stats from it.

没什么复杂的,除了我注意到Sublime Text 3使用Python 3.x以及 ast模块希望也能看到Python 3.x代码.我查看了 ast模块的文档,但找不到任何内容允许我指定版本.

Nothing too complex, except I noticed Sublime Text 3 uses Python 3.x and apparently the ast module expects to see Python 3.x code as well. I looked at the documentation for the ast module but couldn't find anything that allows me to specify the version.

显然,这会在解析完全有效的Python 2.7代码时引起问题.

Obviously this causes issues when parsing perfectly valid Python 2.7 code.

是否可以指定或以某种方式检测/猜测Python版本?还是让解析器更加灵活?

Is there a way to specify or somehow detect/guess the Python version ? Or to allow the parser to be more flexible ?

推荐答案

否,ast模块只能处理其附带的Python版本的Python代码.这是因为在幕后,使用了完全相同的解析器将Python代码编译为字节代码. ast模块所做的只是为您提供中间AST树.该解析器没有向后兼容"模式.

No, the ast module can only handle Python code for the version of Python it is shipped with. That's because under the hood, the exact same parser is used to compile your Python code into byte code; all the ast module does is give you the intermediary AST tree. This parser has no 'backwards compatible' mode.

如果要解析与Python版本不同的源代码,则需要实现自己的解析器.当然,这似乎是 Jedi (Python自动完成库)所采用的路径.

You'll need to implement your own parser if you want to parse different source code from Python versions. This certainly appears the path that Jedi (a Python autocompletion library) took.

查看 SublimeCodeIntel包装中的CodeIntel2 ,我发现软件包基于 SilverCity (具有Python绑定)建立其Python和Python 3解析器.也许该项目将是适合您自己的起点.

Looking at the SublimeCodeIntel packaging of CodeIntel2, I see that that package bases its Python and Python 3 parsers on SilverCity, which has Python bindings. Perhaps that project would be a suitable starting point for your own.

这篇关于如何使用Python 3.x ast模块解析Python 2.x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆