Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>unwind's suggestion of using the ast module in 2.6 is a good one. (There's also the undocumented _ast module in 2.5.) Here's example code for that</p> <pre><code>code = """a = 'blah' b = '''multi line string''' c = u"spam" """ import ast root = ast.parse(code) class ShowStrings(ast.NodeVisitor): def visit_Str(self, node): print "string at", node.lineno, node.col_offset, repr(node.s) show_strings = ShowStrings() show_strings.visit(root) </code></pre> <p>The problem is multiline strings. If you run the above you'll get.</p> <pre><code>string at 1 4 'blah' string at 4 -1 'multi\nline\nstring' string at 5 4 u'spam' </code></pre> <p>You see that it doesn't report the start of the multiline string, only the end. There's no good solution for that using the builtin Python tools.</p> <p>Another option is that you can use my '<a href="http://dalkescientific.com/Python/python4ply.html" rel="nofollow noreferrer">python4ply</a>' module. This is a grammar definition for Python for <a href="http://www.dabeaz.com/ply/" rel="nofollow noreferrer">PLY</a>, which is a parser generator. Here's how you might use it:</p> <pre><code>import compiler import compiler.visitor # from python4ply; requires the ply parser generator import python_yacc code = """a = 'blah' b = '''multi line string''' c = u"spam" d = 1 """ tree = python_yacc.parse(code, "&lt;string&gt;") #print tree class ShowStrings(compiler.visitor.ASTVisitor): def visitConst(self, node): if isinstance(node.value, basestring): print "string at", node.lineno, repr(node.value) visitor = ShowStrings() compiler.walk(tree, visitor) </code></pre> <p>The output from this is</p> <pre><code>string at 1 'blah' string at 2 'multi\nline\nstring' string at 5 u'spam' </code></pre> <p>There's no support for column information. (There is some mostly complete commented out code to support that, but it's not fully tested.) Then again, I see you don't need it. It also means working with Python's 'compiler' module, which is clumsier than the AST module.</p> <p>Still, with a 30-40 lines of code you should have exactly what you want.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload