2011-02-10 22 views
1

我在python2.x以下代码:记号化在python3.x

class _CHAIN(object): 

    def __init__(self, execution_context=None): 
     self.execution_context = execution_context 

    def eat(self, toktype, tokval, rowcol, line, logical_line):   
     #some code and error checking 


operations = _CHAIN(execution_context) 

tokenize(StringIO(somevalue).readline, operations.eat) 

现在的问题是,在python3.x第二个参数不存在。我需要在tokenize之前调用函数operations.eat()。我们如何在python3.x中执行上述任务。一个想法是在'tokenize'语句(代码的最后一行)之前直接调用tokenize.eat()函数。但我不确定要通过的论据。我确定必须有更好的方法来做到这一点。

回答

2

Accoring到http://docs.python.org/py3k/library/tokenize.html,你现在应该使用tokenize.tokenize(readline)

import tokenize 
import io 

class _CHAIN(object): 

    def __init__(self, execution_context=None): 
     self.execution_context = execution_context 

    def eat(self, toktype, tokval, rowcol, line, logical_line):   
     #some code and error checking 
     print(toktype, tokval, rowcol, line, logical_line) 


operations = _CHAIN(None) 

readline = io.StringIO('aaaa').readline 

#Python 2 way: 
#tokenize.tokenize(readline, operations.eat) 

#Python 3 way: 
for token in tokenize.generate_tokens(readline): 
    operations.eat(token[0], token[1], token[2], token[3], token[4]) 
+0

tokenize需要一个可调用的返回字节,而不是字符串(我也犯了这个错误) – 2011-02-10 01:00:42

2

你使用,你传递给函数的迭代与可呼叫可以接受的令牌沿着略显奇怪的遗留系统。新的方式在概念上更简单,并且在这两个Python 2和3的工作原理:

from tokenize import generate_tokens 
for token in generate_tokens(StringIO(somevalue).readline): 
    eat(token) 

这在技术上是没有证件的Python 3,但不可能被拿走。 Python 3中的官方tokenize函数需要字节,而不是字符串。官方的API有a request来标记字符串,但它似乎停滞了。