2

Not sure how I would accomplish overriding the print('something') function do do something else in the class I am in.

For example, I have the following code:

import app
from app.helper import ws_send

class TemplateSubJob:
    def __init__(self, sessiondata, sid, payload):
        self.session = sessiondata
        self.sid = sid
        self.payload = payload

    def startme(self):
        ws_send(self.sid, self.payload, 'Send some output to the user...')
        ws_send(self.sid, self.payload, 'Send something else to the user...')
        print('test')

        return b'xlsx_bytes_output'

I want to override the function print('something') to take what is passed and do something with it.

In my case I want to create a print function that does what ws_send() is doing, except only take a string.

Something like the following:

def print(string):
    ws_send(self.sid, self.payload, string)

print('now i am being sent through ws_send instead of stdout')

How can I accomplish this?

UPDATE:

The reasoning for this is so anyone who is adding code to mine, does not need to modify their code or script to use my functions. I can hijack the print function that they are already using.

user1601716
  • 1,893
  • 4
  • 24
  • 53
  • Why not just add `print` as a method of the class you're using, and call `ws_send.print()` instead? – Tim Sep 19 '18 at 15:51
  • 5
    Out of curiosity: why use `print()` at all then? Why not just define another function that uses `ws_send()`? – Martijn Pieters Sep 19 '18 at 15:52
  • And if put the `print()` function you defined *in the `startme` method*, it would already work exactly as defined. But it'd be better to make it a method, as Tim pointed out. – Martijn Pieters Sep 19 '18 at 15:53
  • If you want to output to a file, use the `file=...` keyword argument in the print function. – N Chauhan Sep 19 '18 at 15:56
  • I am writing code where someone can copy and paste their scripts, i want to overwrite print so they dont have to change their code, my code will just know overwrite print, so they dont have to change all print statements to ws_send – user1601716 Sep 19 '18 at 16:41

3 Answers3

5

You can overload the print function with the following syntax:

from __future__ import print_function
try:
    # python2
    import __builtin__
except ImportError:
    # python3
    import builtins as __builtin__


def print(*args, **kwargs):
    __builtin__.print('New print function')
    return __builtin__.print(*args, **kwargs)

E: Fixed bad import, as pointed out in the comment

Tim
  • 2,756
  • 1
  • 15
  • 31
  • ...what? `from builtins import __builtin__`? No, it's just `import builtins`, or `import __builtin__` on Python 2. The `builtins` module itself (or the `__builtin__` module on Python 2) is the built-ins namespace, not `builtins.__builtin__`. You got mixed up somewhere. – user2357112 Sep 19 '18 at 15:56
  • 1
    in python 2, you probably need the "futures" import print_function stuff. – Jean-François Fabre Sep 19 '18 at 15:59
3

So I'm not going to go over the why you're using a print statement in that given case, but for Python 3, within your class description

class TemplateSubJob:
    def __init(self, ):
        # and other methods

    def __str__(self, ):
      return 'String description here'

which will return the given string when someone tries to print the given object. For example, when I instantiate, I can then call the print function directly following the instantiation, which will return any strings returned by the str function above

    myobject = TemplateSubJob()
    print(myobject)
Aadi
  • 63
  • 5
  • 1
    Hello... Inspect // Watch ... Your answer is poorly elaborated. It is useful to insert an effective response, with codes and references. Concluding a practical and efficient solution. This platform is not just any forum. We are the largest help and support center for other programmers and developers in the world. Review the terms of the community and learn how to post; – Paulo Boaventura Mar 24 '21 at 19:40
  • Did, added another snipped showing where to place the function and how to call it, hopefully that cleared it up? – Aadi Mar 25 '21 at 08:56
1

For redirecting print to variable(string), use this:

from io import StringIO # Python2 use: from cStringIO import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()

Source: https://stackoverflow.com/a/1218951/4718434

For redirect it to file, use this:

https://stackoverflow.com/a/4675744/4718434

yaya
  • 7,675
  • 1
  • 39
  • 38
  • Wouldn't it be better to use [contextlib.redirect_stdout](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout) instead of _this_? – 0xC0000022L Oct 18 '22 at 10:49