本文介绍了ast和App Engine之间的ast的col_offset是否不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在App Engine Python3.7环境上的项目尝试使用ast模块:

My project on App Engine Python3.7 environment tried using ast module:

from flask import Flask, request
import ast

app = Flask(__name__)

@app.route('/', methods=['GET'])
def respond():
    code = '''
if True:
    pass
elif True:
    pass
elif False:
    pass
else:
    pass
'''
    module_node = ast.parse(code)
    visitor = MyVisitor()
    visitor.visit(module_node)
    return visitor.result

class MyVisitor(ast.NodeVisitor):
    def visit_If(self, node):
        self.result = '{} {} {} {}'.format(
            node.col_offset,
            node.orelse[0].col_offset,
            node.orelse[0].orelse[0].col_offset,
            node.orelse[0].orelse[0].orelse[0].col_offset
        )

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)

结果在本地为"0 5 5 4"(在macOS 10.15.4上为Python3.7.4).但是,App Engine返回了"0 0 0 4".我该如何解决?我需要ast来解析代码并生成另一个表示形式.谢谢.

The result was '0 5 5 4' on local (Python3.7.4 on macOS 10.15.4). However App Engine returned '0 0 0 4'. How can I resolve this? I need ast to parse code and generate another representation. Thank you.

推荐答案

在Python 3.7.6和Python 3.7.7之间看起来像这样改变了:

Looks like this changed between Python 3.7.6 and Python 3.7.7:

import ast
import sys


class MyVisitor(ast.NodeVisitor):
    def visit_If(self, node):
        self.result = '{} {} {} {}'.format(
            node.col_offset,
            node.orelse[0].col_offset,
            node.orelse[0].orelse[0].col_offset,
            node.orelse[0].orelse[0].orelse[0].col_offset
        )


code = '''
if True:
    pass
elif True:
    pass
elif False:
    pass
else:
    pass
'''
module_node = ast.parse(code)
visitor = MyVisitor()
visitor.visit(module_node)
print(sys.version)
print(visitor.result)
$ python3.7.6 test.py
3.7.6 (default, May 20 2020, 09:51:40)
[Clang 11.0.0 (clang-1100.0.33.16)]
0 5 5 4

$ python3.7.7 test.py
3.7.7 (default, Apr 24 2020, 10:25:06)
[Clang 11.0.0 (clang-1100.0.33.16)]
0 0 0 4

在撰写本文时,App Engine的python37运行时使用Python 3.7.7和通常会在发布时升级到最新的补丁程序版本.

At the time of writing, App Engine's python37 runtime uses Python 3.7.7 and is generally upgraded to the latest patch version as it is released.

我希望较新版本的Python的行为在此更为正确",实际上,这种行为在3.8和3.9中也将持续存在:

I would expect the behavior of the newer version of Python to be more "correct" here, and in fact this behavior persists through 3.8 and 3.9 as well:

$ python3.8 test.py
3.8.2 (default, Apr 22 2020, 21:21:01)
[Clang 11.0.0 (clang-1100.0.33.16)]
0 0 0 4

$ python3.9 test.py
3.9.0a5 (default, Apr 24 2020, 10:32:31)
[Clang 11.0.0 (clang-1100.0.33.16)]
0 0 0 4

这篇关于ast和App Engine之间的ast的col_offset是否不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:38