<p>要理解多行代码实际上是一行python代码,您需要一些理解python的东西。你知道吗</p>
<p>在python中,您可以从代码获取编译器。“compile”命令可以获取文本并返回代码对象,或者在代码语法不正确时抛出错误:</p>
<pre><code>try:
compile(candidate_code, 'fake filename', 'exec')
# got here? candidate_code compiles
except:
# got here? candidate_code doesn't compile
</code></pre>
<p>编译完全可以容忍缺少符号定义的情况。但是,它不喜欢看到额外的缩进。你知道吗</p>
<p>使用它,我们可以逐步遍历代码行,查找多行语句(成功编译的行组)并测试任何为目标字符串编译的语句。我们必须将所有行编译到当前行(否则如果您的语句缩进,它就不会编译),并跟踪实际测试的行数(使用numcandidatelines)。另一种方法可能是简单地检测并去除多余的压痕。你知道吗</p>
<pre><code>def findPythonLines(aContainsStr, lines):
numcandidatelines = 0
for index, line in enumerate(lines):
numcandidatelines += 1
try:
candidate_code = "\n".join(lines[:index+1])
candidate_statement = "\n".join(lines[index+1-numcandidatelines: index+1])
compile(candidate_code, 'fake filename', 'exec') # or 'exec'
# if we get here, this is a new possible result
if aContainsStr in candidate_statement:
return candidate_statement
else:
# no dice. Well, we need to look for the next candidate
numcandidatelines = 0
except:
pass
return None
# say input.txt contains the following:
# x = 10
#
# while (x
# > 0):
# g()
#
# y = f(Name='MANHOLE', Values=[ 1, 2, ],
# var='LV')
#
# x -= 1
with open ("input.txt", "r") as myfile:
full_code_lines=myfile.readlines()
print "result: %s" % findPythonLines("'LV'", full_code_lines)
# prints out the following:
#
# result:
# y = f(Name='MANHOLE', Values=[ 1, 2, ],
# var='LV')
</code></pre>