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.

2
  • Look at the : colon; it indicates an indentation level is expected to increase.. Commented Mar 7, 2013 at 10:09
  • Other than that, you probably want to start with the ast parse tree to get a much better feel for the meaning of the code. Or switch to using decorators on your classes and functions instead of inserting print statements everywhere. Commented Mar 7, 2013 at 10:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.