How to differentiate between “a string” and “a actual code” in python?

前端 未结 2 1598
情话喂你
情话喂你 2020-12-21 23:42

My works relates to instrumentation of code fragments in python code. So in my work i would be writing a script in python such that I take another python file as input and i

2条回答
  •  清酒与你
    2020-12-21 23:51

    You could use a Regular Expression. To avoid def inside quotes then you can use negative look-arounds:

    import re
    
    for line in open('A.py'):
        m = re.search(r"(?!<[\"'])\bdef\b(?![\"'])", line)
        if m:
            print r'@decorator    #<------ inserted code' 
    
        print line 
    

    However, there might be other occurances of def that you or I can't think of, and if we are not careful we end-up writing the Python parser all over again. @Janne Karila's suggestion of using ast.parse is probably safer in the long term.

提交回复
热议问题