你讓兩個錯誤:
- generate_tokens返回一個迭代,而不是一個列表,所以你需要以交互方式顯示結果(編程訪問的希望發生器的形式)與
list()
把它包起來。
- 參數不是一個字符串,而是返回字符串的調用,以在
ipython
file().readline
固定碼和輸出的方式,因此很版畫列出更好:
In [1]: from tokenize import generate_tokens
In [2]: from cStringIO import StringIO
In [3]: list(generate_tokens(StringIO('hello this is a test string').readline))
Out[3]:
[(1, 'hello', (1, 0), (1, 5), 'hello this is a test string'),
(1, 'this', (1, 6), (1, 10), 'hello this is a test string'),
(1, 'is', (1, 11), (1, 13), 'hello this is a test string'),
(1, 'a', (1, 14), (1, 15), 'hello this is a test string'),
(1, 'test', (1, 16), (1, 20), 'hello this is a test string'),
(1, 'string', (1, 21), (1, 27), 'hello this is a test string'),
(0, '', (2, 0), (2, 0), '')]
對於下一級別(解析),請使用標準ast
模塊或第三方logilab.astng
包。