PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] How to override the builtin method "print()"

 September 15, 2022     printing, python     No comments   

Issue

I need to customize the print(), so that it does something else besides printing what I want. Is there a way to override it?


Solution

one option is to use contextlib.redirect_stdout:

from contextlib import redirect_stdout

with open('file.txt', 'a') as file, redirect_stdout(file):
    print('hello')

if you need both printing and saving to a file, this may work:

from contextlib import redirect_stdout
from sys import stdout
from io import StringIO

class MyOutput(StringIO):
    def __init__(self, file):
        super().__init__()
        self.file = file

    def write(self, msg):
        stdout.write(msg)
        self.file.write(msg)

with open('file.txt', 'a') as file, redirect_stdout(MyOutput(file=file)):
    print('hello')


Answered By - hiro protagonist
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,255,117

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing