portable /dev/null again

Skip Montanaro skip at pobox.com
Wed Mar 24 15:43:50 EST 2004


>>>>> "John" == John Belmonte <john at neggie.net> writes:

    John> Skip Montanaro wrote:
    >> How about:
    >> 
    >> class nullFile:
    >>     def _null(self, *args, **kwds):
    >>         pass
    >> 
    >> def __getattr__(self, name):
    >>     return self._null

    John> Unless I'm misunderstanding your code, this object is not going to
    John> give me a legitimate file descriptor that I can pass to another
    John> program.

In general you can't pass file descriptors between programs.  If you want
something that simulates /dev/null as a data sink the class I posted should
work just fine:

    class nullFile:
        def _null(self, *args, **kwds):
            pass

        def __getattr__(self, name):
            return self._null

    null = nullFile()

    for i in range(10):
        print "/etc/services to null file"
        null.write(file("/etc/services").read())

While I agree you can open /dev/null for reading, it's rarely used that way.

If you want something that returns an honest-to-god file object, how about:

    import os
    def nullfile(mode="wb"):
        return file(os.path.exists("/dev/null") and
                    "/dev/null" or
                    "nul:", mode)

    null = nullfile()

    for i in range(10):
        print "/etc/services to null file"
        null.write(file("/etc/services").read())

?

Guido made an astute observation the other day which I can't find at the
moment.  It went something like, "The biggest problem I have now is
convincing people that just because something's not already in the standard
library doesn't mean it belongs there."  I suspect this applies.  If a
portable null file object is the cats pajamas for you, write something and
throw it in your personal toolbox or post it to your personal Python page
where others can find it.

Skip




More information about the Python-list mailing list