1

I want to keep track of the last time my python program printed something to the console.

I created this function:

def updateLastPrintTime():
    global lastPrintTime
    lastPrintTime = time.time()

And I'm calling it after each print statement.

This works fine, however, I have a lot of print statements and I want to update lastPrintTime after each and every printing.

If print was not a built in function, this is what I would do:

def print():
    updateLastPrintTime()
    # rest of 'print' code ...

But I can't figure out how to do that with a built-in function, especially since they are written in C. Any help would be appreciated.

Sky
  • 379
  • 3
  • 13

2 Answers2

1

You can assign the builtins print to another name and then you can override print

_print = print
def print(*args, **kwargs):
    _print("Hello,", *args, **kwargs)

print("world!")

Alternatively, you can also get the builtins print from the builtins module e.g.

import builtins
def print(*args, **kwargs):
    builtins.print("Hello,", *args, **kwargs)

print("world!")
tomjn
  • 5,100
  • 1
  • 9
  • 24
  • This is the direction that I'm looking for, but both are giving me ```invalid syntax``` on lines ```def print(*args, **kwargs):``` and ```_print = print``` – Sky Sep 30 '19 at 11:00
  • @Sky what version of python are you using? – tomjn Sep 30 '19 at 11:01
  • I'm using python 2.7 – Sky Sep 30 '19 at 11:30
  • @Sky, ok your description of `print` as a function confused me. You should look at the answer from @Dan below (or the linked answer). The answer I gave only works for python 3. – tomjn Sep 30 '19 at 11:46
1

Based on this answer: overload print python

You could do something like this:

from __future__ import print_function

import time

last_print_time = time.time()  # initialise global var

try:
    import __builtin__
except ImportError:
    # Python 3
    import builtins as __builtin__

# overload the print function
def print(*args, **kwargs):
    global last_print_time
    last_print_time = time.time()  # update variable
    return __builtin__.print(*args, **kwargs)  # print the message
Dan
  • 1,575
  • 1
  • 11
  • 17