Sorry for my English. This problem is complicated, and my English isn't thats good to describe everything clearly.
Ok, I have this example code. This is only a small code, in real environment i operate on much larger code than that.
01: multi_line_string = """Abc
02: Dfg
03: Hjk"""
04: # Comment
05: do_somethingA()
06: do_somethingB()
07: do_somethingC()
08: string_with_linebrak = "Abc \
09: Dfg \
10: Hjk"
This code, each line as list element i get as argument in my function with one line number. In result i need to return list of 2 lines around given line number. For example, with this code i get line number 5. This is do_somethingA()
line.
My function must return list with 5 elements - 2 lines before line 5, line 5 and 2 lines after line 5. That is:
03: Hjk"""
04: # Comment
05: do_somethingA()
06: do_somethingB()
07: do_somethingB()
As you see in return i have broken Python code. Unfortunately, I must get complete code. So, I need somehow detect that line 3 are not complete line of Python code and i need to detect where this broken line ar开发者_开发百科e started or ended and get all lines along the way. So, what i need is:
01: multi_line_string = """Abc
02: Dfg
03: Hjk"""
04: # Comment
05: do_somethingA()
06: do_somethingB()
07: do_somethingC()
Lexing complete code is not an option, I need most CPU efficient way to do this.
I would suggest looking at pylint.
Get the abstract syntax tree. http://docs.python.org/library/ast.html
Walk the tree inserting "previous statement"/"next statement" links from each node to the previous statement node. And from the previous statement to the current statement.
How this will work with compound statements (for, while, if, try, with, def, class) is beyond me.
Break from this two statements after the required line number.
Go back two statements. Dump the 5 statements that start from the current position in the tree.
精彩评论