inherit from file and create stdout instance?

7stud bbxx789_05ss at yahoo.com
Tue May 15 19:02:58 EDT 2007


On May 15, 4:18 pm, MisterPete <pete.losange... at gmail.com> wrote:
> How can I inherit from file but stil create an instance that writes to
> stdout?
> -----------
>      I'm writing a file-like object that has verbosity options (among
> some other things). I know I could just set self.file to a file object
> rather than inheriting from file. I started with something like this
> (simplified for clarity):
>
> class Output(object):
>     def __init__(self, file=sys.stdout, verbosity=1):
>         self.verbosity = verbosity
>         self.file = file
>
>     def write(self, string, messageVerbosity=1):
>         if messageVerbosity <= self.verbosity:
>             self.file.write(string)
> ...
>
>      but it is frustrating me that if I try to inherit from file it
> works fine for regular files but I can't figure out a clean way to
> instantiate an object that writes to stdout using sys.stdout.
> something like the following:
>
> class Output(object):
>     def __init__(self, file=sys.stdout, verbosity=1):
>         self.verbosity = verbosity
>         self.file = file
>
>     def write(self, string, messageVerbosity=1):
>         if messageVerbosity <= self.verbosity:
>             self.file.write(string)
> ...
>
> I hope that's clear. Is it just a bad idea to inherit from file to
> create a class to write to stdout or am I missing something? Any
> insight is appreciated.
>
> Thanks,
> Pete

Your code works for me:


import sys

class Output(file):
    def __init__(self, file=sys.stdout, verbosity=1):
        self.verbosity = verbosity
        self.file = file

    def write(self, string, messageVerbosity=1):
         if messageVerbosity <= self.verbosity:
             self.file.write(string)

o = Output()
o.write("this goes to a console window")

f = open("aaa.txt", "w")
o = Output(f)
o.write("this goes to a file")






More information about the Python-list mailing list