how to store result of sys.stdout.write in a global variable in Python

Amit Gupta Source

How can I use the result of sys.stdout.write(output) as a global variable. Following is the part of the code. output of sys.stdout.write is words and it keeps appending till 140 characters are completed.

for i in range(140):
    x = numpy.reshape(pattern, (1, len(pattern), 1))
    x = x / float(num_vocab)
    pred = model.predict(x, verbose=0)
    index = numpy.argmax(pred)
    output = int_to_char[index]
    seq_in = [int_to_char[value] for value in pattern]
    pattern = pattern[1:len(pattern)]


answered 6 months ago abarnert #1

The result of sys.stdout.write isn't very useful—it's just the number of characters in whatever you wrote. Of course you can store that in a global variable:

written = 0

def myfunc():
    global written
    written += sys.stdout.write(blahblah)

… but I can't see why you'd want to.

What sys.stdout.write writes to the terminal (or redirected file, or whatever) seems a lot more useful. But you already have that. You're doing this:


So, what it writes is going to be exactly what's in output. So just store that. For example:

outputs = []
def myfunc():
    global outputs
    output = blah blah blah

Now, if you have no control over the function that's writing stuff, because it's in some library that you're not allowed to modify or something, you can capture its output. This is usually not a good idea, but if you need to, you can write a wrapper around the real sys.stdout that saves the output and then passes it through to the real thing (or doesn't, if you don't want it to hit the screen), and then just assign sys.stdout = mywrapper. But if you can't figure out how to write that, you almost certainly don't want to.

comments powered by Disqus