0

I am reverse engineering a python application. Through which i will be observing the behavior by dynamically instrumenting code inside the application. The problem is i need to insert the code at the correct level of indentation.

For example lets consider a fragment of code i will be instrumenting:

class A:
     def move(self,name):
         name=self.name
         print name
     def move1(self):
         print 'dude'

Now for the above sample code i will be instrumenting entry and exit logging and the instrumented code should look like this below

enter code class A:
     def move(self,name):
         print 'Entry move class='A''
         name=self.name
         print name
         Print'Exit move class='A''
     def move1(self):
         print 'Entry move1 class='A''
         print 'dude'
         print 'Exit move class='A''

This what i need when instrument the code instead i get the following:

enter code class A:
     def move(self,name):
print 'Entry move class='A''
             name=self.name
             print name
print'Exit move class='A''
         def move1(self):
print 'Entry move1 class='A''
             print 'dude'
print'Exit move1 class='A''

Because i am writing a script it insert into the next line and doesnt know the indentation format for a python code.

Is there anyway i could automatically adjust the indentation while inserting or i should need to know the index of the character in the next line and insert spaces to the string and then insert.

hakre
  • 193,403
  • 52
  • 435
  • 836
Kaushik
  • 1,264
  • 8
  • 20
  • 32
  • Look at the `:` colon; it indicates an indentation level is expected to increase.. – Martijn Pieters Mar 07 '13 at 10:09
  • Other than that, you probably want to start with the [`ast` parse tree](http://docs.python.org/2/library/ast.html) to get a *much better* feel for the meaning of the code. Or switch to using [decorators](http://stackoverflow.com/questions/739654/understanding-python-decorators) on your classes and functions instead of inserting print statements everywhere. – Martijn Pieters Mar 07 '13 at 10:13

1 Answers1

1

In your example, it's actually fairly easy:

  • The "entry" message should have exactly the same indentation as the statement that follows it.

  • The "exit" message should have exactly the same indentation as the corresponding "entry" message.

That said, you can simplify the job considerably by using a decorator instead of the two explicit print statements. Something like @trace from this page is much easier to insert into the code than pairs of prints.

To take things even further, instead of modifying the source files, you could perform the instrumentation on the fly.

NPE
  • 486,780
  • 108
  • 951
  • 1,012