开发者

is it possible to call a function every x-number of lines that get interpreted?

I am trying to do a progress bar.

Would it be possible to count the number of execution lines on a script and associate each execution line with a function so that it is executed every line or ev开发者_如何学JAVAery 5 lines?

My plan is to update a progress bar every time a line is executed.

Is it possible? Can I use decorators to do it?


Yep, you can do that by asking Python to alert you every time it processes a line. Here's an example that prints to stdout after every updatelines times a line is executed:

import sys

class EveryNLines(object):
    def __init__(self, updatelines):
        self.processed = 0
        self.updatelines = updatelines

    def __call__(self, frame, event, arg):
        if event == 'line':
            self.processed += 1
            if not self.processed % self.updatelines:
                print 'do something'
        return self

def testloop():
    for i in range(5):
        print i

oldtracer = sys.gettrace()
sys.settrace(EveryNLines(3))
testloop()
sys.settrace(oldtracer)

You could certainly turn that into a decorator for convenience.


Could you benefit from an Observer object?

class Observer(object):
 def __init__(self):
   self._subjects = []
 def add_subject(self, subject):
   self._subjects.append(subject)
 def notify(self, percentage):
   for subject in self._subjects:
    subject.notify(percentage)

class Subject(object):
  def notify(self, percentage):
   # in this example, I assume that you have a class
   # that understand what does "update_progress_bar(%)" means
   # and it is inheriting from `Subject`
   self.update_progress_bar(percentage)

s = Subject()
o = Observer()
o.add_subject(s)
# your code

def my_fun():
 blah()
 blah2()
 o.notify(20)
 blah3()
 o.notify(30)
 blah4()
 o.notify(100)

So, you create an Observer class whose only purpose is to keep track of the runtime. You can create one or several Subject objects which can be notified by the Observer: in this case they get notified the percentage completion. When each Subject gets notified, they can do whatever they want to, like update a progress bar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜