[英]How to differentiate between “a string” and “a actual code” in python?
我的作品涉及python代碼中的代碼片段檢測。 因此,在我的工作中,我將使用python編寫腳本,以便我將另一個python文件作為輸入,並在腳本的所需位置插入任何必要的代碼。
以下代碼是我要檢測的文件的示例代碼:
A.py #normal un-instrumented code
statements
....
....
def move(self,a):
statements
......
print "My function is defined"
......
statements
......
我的腳本的實際作用是檢查A.py中的每一行,如果有“ def”,則將代碼片段插入def函數的代碼之上
以下示例是最終輸出的方式:
A.py #instrumented code
statements
....
....
@decorator #<------ inserted code
def move(self,a):
statements
......
print "My function is defined"
......
statements
......
但是我得到的結果卻不同。 以下代碼是我得到的最終輸出:
A.py#儀器代碼
statements
....
....
@decorator #<------ inserted code
def move(self,a):
statements
......
@decorator #<------ inserted code [this should not occur]
print "My function is defined"
......
statements
......
我可以理解,在已檢測的代碼中,它可以識別單詞“ defined”中的“ def”,因此可以檢測其上方的代碼。
實際上,檢測到的代碼有很多這樣的問題,我無法正確檢測給定的python文件。 還有其他方法可以將實際的“ def”與字符串區分開嗎?
謝謝
使用ast
模塊正確解析文件。
此代碼顯示每個def
語句的行號和列偏移量:
import ast
with open('mymodule.py') as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
print node.lineno, node.col_offset
您可以使用正則表達式。 為了避免在引號中使用def
,那么您可以使用否定環顧:
import re
for line in open('A.py'):
m = re.search(r"(?!<[\"'])\bdef\b(?![\"'])", line)
if m:
print r'@decorator #<------ inserted code'
print line
但是,可能還有其他一些您可能無法想到的def
發生,並且如果我們不小心的話,最終將重新編寫Python解析器。 從長遠來看,@ Janne Karila建議使用ast.parse
可能更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.