简体   繁体   中英

suppressing print as stdout python

Ok.. So probably an example is a good way to explain this problem

So I have something like this:

if __name__=="__main__"
    result = foobar()
    sys.stdout.write(str(result))
    sys.stdout.flush()
    sys.exit(0)

Now this script is being called from a ruby script.. and basically it parses the result there. But foobar() has a lot of print statments.. and stdout flushes all those prints as well. Is there a way (besides logging mathods) I can modify something over here which automatically suppresses those prints and just flushes this result?? Thanks

You want to shadow (or otherwise hide) the stdout temporarily. Something like this:

actualstdout = sys.stdout
sys.stdout = StringIO()
result = foobar()
sys.stdout = actualstdout
sys.stdout.write(str(result))
sys.stdout.flush()
sys.exit(0)

You need to assign something that is file-like to sys.stdout so that other methods can use it effectively. StringIO is a good candidate because it doesn't require disk access (it'll just collect in memory) and then is discarded.

With Python 3.4 and up you can use the redirect_stdout contextmanager like this:

with redirect_stdout(open(os.devnull, "w")):
    print("This text goes nowhere")
print("This text gets printed normally")
import sys

class output:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)


if __name__=="__main__":

    out = output()                   
    sys.stdout = out                   #redirecting the output to a variable content

    result = foobar()
    sys.stdout.write(str(result))
    sys.stdout.flush() 

    sys.stdout = sys.__stdout__        #redirecting the output back to std output   
    print "o/p of foo :",out.content

    sys.exit(0)

This link shows how to redirect stdout in python . Redirect it to an internal pipe, then read your pipe and filter out the unwanted lines. That will let you keep only the lines you are interested in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM