[Tutor] nul file in Windows

Dave Angel davea at ieee.org
Sun Nov 15 15:12:38 CET 2009


Timo List wrote:
> For my program I disable the py2exe log feature by routing output to the
> nul-file.
> Code:
>
>         if win32 and py2exe:
>             sys.stdout = open("nul", "w")
>             sys.stderr = open("nul", "w")
>
> This always worked fine.
>
> Today, I received an email from a user with the following error:
> IOError: [Errno 2] No such file or directory: 'nul'
>
> Now, I thought the nul-file always existed, shouldn't it?
> Is there another way to disable output, if this one fails?
>
> Cheers,
> Timo
>
>   
All you need is an object that behaves like a file, but does nothing 
with the data sent to it.  That's what duck-typing is all about.

I haven't tried it, but I'd start by making a new class:

class  NullFile(object):
    def __init__(self, *arg, **kwarg):
             pass
    def write(self, data, *arg, **kwarg):
            pass
     def close(self, *arg, **kwarg):
           pass

and just say
    sys.stdout = NullFile()

If you get any exceptions, you could add new methods to this file, 
accordingly.


DaveA



More information about the Tutor mailing list