我试图用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获取一些代码,如果它是从类方法缩进的。 –