Python Encapsulate the Print Function for a Variable

If I have a function containing many print statements:

t

def funA():
  print "Hi"
  print "There"
  print "Friend"
  print "!"

I want to do something like this

def main():
  ##funA() does not print to screen here
  a = getPrint(funA()) ##where getPrint is some made up function/object
  print a ##prints what funA would normally print at this step

So, when funcA is called, it does not do any printing, but prints it to an object. Then I print the object to get the result. Is there any way to do this? I also do not want to touch the original function.

Hope this makes sense.

+3
source share
6 answers

You can do almost what you want, as long as you don't mind a slight difference in syntax:

import cStringIO
import sys

def getPrint(thefun, *a, **k):
  savstdout = sys.stdout
  sys.stdout = cStringIO.StringIO()
  try:
    thefun(*a, **k)
  finally:
    v = sys.stdout.getvalue()
    sys.stdout = savstdout
  return v

, getPrint(funA), not getPrint(funA()) - , , getPrint .

, getPrint ( , getPrint!).

+7
from cStringIO import StringIO

def getPrint(func, *args, **kwds):
  old_stdout = sys.stdout
  sys.stdout = StringIO()
  try:
    func(*args, **kwds)
  except:
    raise
  else:
    return sys.stdout.getvalue()
  finally:
    sys.stdout = old_stdout

#...
a = getPrint(funA) # notice no (), it is called by getPrint
print a.rstrip("\n") # avoid extra trailing lines
+3

-

from contextlib import contextmanager
import StringIO
import sys

@contextmanager
def capture():
    old_stdout = sys.stdout
    sys.stdout = StringIO.StringIO()
    try:
        yield sys.stdout
    finally:
        sys.stdout = old_stdout

:

with capture() as c:
    funA()
    funB()
    print 'HELLO!'

:

print c.getvalue()
+2

sys.stdout .

+1

Use cStringIO (see doc ).

from cStringIO import StringIO

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

getPrint( funA() )
# use mystdout to get string
+1
source

The simplest thing is to change funA()so that you don’t print anything, but simply return the string values.

Same:

def funA():
    return "Hi\n" + "There\n" + "Friend\n" + "!\n"

# later:
print(funA())

It is always easy to collect lines and print them; he tricks to collect lines when they are printed.

If you have a huge number of existing printing features, then yes, use one of the tricks provided here to collect the results.

0
source

Source: https://habr.com/ru/post/1726945/


All Articles