Luke
Luke

Reputation: 553

I need to overwrite the stdout for one line, and then revert the change

This is what I have:

cfd1 = nltk.ConditionalFreqDist(biglisttagged)
sys.stdout = open(corpus_name+"-pos-word-freq.txt",'w')
cfd1.tabulate()
sys.stdout = sys.__stdout__ #this is supposed to revert the change, but it doesn't.

print("helloword") #I need this to print to stdout

This is because tabulate() automatically writes to stdout, and I need it to write to the file.

However, my problem is this makes stdout not work for anything else in the program.

In the above example, helloworld would not get printed, what do I need to change?

Upvotes: 0

Views: 70

Answers (4)

yorammi
yorammi

Reputation: 6458

You can solve this by calling the script that redirect the stdout to a file and gets the relevant values as arguments and then continue the flow in the calling script without redirecting the stdout:

test1.py

    import sys
    cfd1=sys.argv[1]
    sys.stdout = open(corpus_name+"-pos-word-freq.txt",'w')
    cfd1.tabulate()

test2.py

cfd1 = nltk.ConditionalFreqDist(biglisttagged)
execfile("test1.py " + cfd1)
print("helloword")

Upvotes: 0

Dunes
Dunes

Reputation: 40778

How are you running this? I get this behaviour on IDLE, where the normal stdout has been replaced, and __stdout__ set to None.

You could use unittest.mock.patch to handle the temporary redirect of stdout for you. Using the with statement means that stdout will be reset, even if there is an exception in your code block.

from unittest.mock import patch

cfd1 = nltk.ConditionalFreqDist(biglisttagged)

with open(corpus_name+"-pos-word-freq.txt", "w") as redirect, \
        patch("sys.stdout", new=redirect):
    cfd1.tabulate()

print("helloword")

Upvotes: 0

Pedro
Pedro

Reputation: 409

Try:

cfd1 = nltk.ConditionalFreqDist(biglisttagged)
stdout_save = sys.stdout
sys.stdout = open(corpus_name+"-pos-word-freq.txt",'w')
cfd1.tabulate()
sys.stdout = stdout_save

print("helloword") #I need this to print to stdout

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114038

sys_stdout  = sys.stdout
sys.stdout = open(...)
...
sys.stdout = sys_stdout

Upvotes: 1

Related Questions