我試圖用AST解析一些代碼,但由於反斜槓延續字符,我遇到問題。刪除反斜槓延續字符
當我有一個接續字符\,textwrap將無法設置縮進代碼,我想知道如何擺脫它。
code = """
def foo():
message = "This is a very long message that will probably need to wrap at the end of the line!\n \
And it actually did!"
"""
import textwrap
print textwrap.dedent(code)
import ast
ast.parse(textwrap.dedent(code))
我添加更多的細節,澄清問題:
我有以下內容的模塊nemo.py:
class Foo(object):
def bar(self):
message = "This is a very long message that will probably need to wrap at the end of the line!\n \
And it actually did!"
,並試圖解析代碼的主要模塊:
import ast
import nemo
import inspect
import textwrap
code = str().join(inspect.getsourcelines(nemo.Foo.bar)[0])
ast.parse(textwrap.dedent(code))
而且回溯:
Traceback (most recent call last):
File "/Users/kelsolaar/Documents/Development/Research/_BI.py", line 7, in <module>
ast.parse(textwrap.dedent(code))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
def bar(self):
^
IndentationError: unexpected indent
你爲什麼dedenting的代碼? –
你可能想要'\\ n',而不是'\ n'。 – georg
因爲我有一個從ast的縮進錯誤,否則。我正在用inspect.getsourcelines獲取一些代碼,如果它是從類方法縮進的。 –