Exception ValueError: "I / O operation on uninitialized object" on

We have a little test automation process called run.py at work and inside the file there is a class called

class flushfile(io.TextIOWrapper):
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

      

it gives this error:

Exception ValueError: 'I/O operation on uninitialized object' in

      

Every time we run tests but it doesn't seem to have any effect. The context of the class is that we delete the buffer after printing to a text file and also on the command line.

sys.stdout = flushfile(sys.stdout)

      

How it is called in the code.

In life, I cannot understand what it can be.

+3


source to share


1 answer


You have to add a method flush()

to your shell:

class flushfile(io.TextIOWrapper):
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()
    def flush(self):
        self.f.flush()

      

Simple test:

import sys
sys.stdout = flushfile(sys.stdout)
print("TEST")

      

Without flush()

you get an error if the script is dead and try calling a flush()

new one sys.stdout

.

Anyway with the original version, if you restore stdout

before exiting, you can get the same result:

import sys
orig = sys.stdout
sys.stdout = flushfile(sys.stdout)
print("TEST")
sys.stdout = orig

      




EDIT

Maybe you don't need to wrap for the file object, just a new method write()

. Python is primarily a functional programming language, and the simpler pythoninc way to do what you want to do is change the method sys.stdout.write

. Follow the example implementation:

def make_write_flusher(f):
    orig = f.write
    def new_write(data):
        orig(data)
        f.flush()
    f.write = new_write

import sys
make_write_flusher(sys.stdout)
print("TEST")

      

The last consideration is that if you call super

in your original implementation that will fix the problem, but the real thought is that you are not really using a wrapper and both of the following implementations give the same result. In a Python interface, it doesn't really matter what matters if the attribute / methods are present and what you use.

class flushfile(io.TextIOWrapper):
    def __init__(self, f):
        super(flushfile,self).__init__(f)
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

class flushfile():
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()
    def flush(self):
        self.f.flush()

      

+2


source







All Articles