2012-11-09 109 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))