2012-11-09 107 views
1

我试图用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 
+0

你为什么dedenting的代码? –

+0

你可能想要'\\ n',而不是'\ n'。 – georg

+0

因为我有一个从ast的缩进错误,否则。我正在用inspect.getsourcelines获取一些代码,如果它是从类方法缩进的。 –

回答

2

这是因为您误解了textwrap.dedent()的功能。

删除任何共同领先的空格。在你的情况下,没有共同的领先空白,因此没有任何东西被删除。

此外,在这种情况下,你想要的实际上是\\而不是\n \。这是因为你真的想要打印被解析。 \\将只打印一个\,这是你想要的。 \n \将在"..."子句内打印一条无效的新行。

现在考虑下面的代码:

>>> code = """ 
    def foo(): 
     message = "This is a very long message that will probably need to wrap at the end of the line! \\ 
    And it actually did!" 
""" 

>>> print textwrap.dedent(code) 

def foo(): 
    message = "This is a very long message that will probably need to wrap at the e 
nd of the line! \ 
And it actually did!" 

>>> ast.parse(textwrap.dedent(code)) 
<_ast.Module object at 0x10e9e5bd0> 

在这种情况下,有共同领先的空格,因此它们将被删除。


编辑:

如果你想摆脱\的都在一起,你可以考虑使用def bar"""My sentence"""message

+0

我更新了我的问题,因为它错过了关于我想实现的重要细节,并且我理解什么是textwrap.dedent :) –

+0

@KelSolaar我更新了我的答案,关键是您可以使用'“ “”''作为消息而不是'\'。 –

+0

是的,我明白了,欢呼!我会将你的回答标记为有效,因为它解决了我第一次描述的问题 –

0

对于这个问题我下面的简单替代的第二部分涉及我的需求:code.replace( “\\ N”,STR())

import ast 
import nemo 
import inspect 
import textwrap 

code = str().join(inspect.getsourcelines(nemo.Foo.bar)[0]) 
code.replace("\\\n", str()) 
ast.parse(textwrap.dedent(code))