Portable way to refer to the null device?

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Feb 6 23:07:09 EST 2009


Roy Smith <roy at panix.com> writes:

> I need to run a command using subprocess.Popen() and have stdin
> connected to the null device.  On unix, I would do:
> 
>         self.process = subprocess.Popen(argv,
>                                         env=new_env,
>                                         stdout=open(outfile, 'w'),
>                                         stderr=open(errfile, 'w'),
>                                         stdin=open('/dev/null')
>                                         )

Yikes, that's a nasty indentation you've got going on there. I'd be
writing the above as:

    self.process = subprocess.Popen(
        argv,
        env=new_env,
        stdout=open(outfile, 'w'),
        stderr=open(errfile, 'w'),
        stdin=open('/dev/null'),
        )

> but that's not portable to windows.  Does Python have a portable way
> to get a file object connected to the null device, regardless of what
> operating system you're running on?

Almost: the ‘os.devnull’ attribute is documented (in the documentation
for the ‘os’ module) as “os.devnull is the file path of the null
device ('/dev/null', etc.)”.

So the above becomes:

    self.process = subprocess.Popen(
        argv,
        env=new_env,
        stdout=open(outfile, 'w'),
        stderr=open(errfile, 'w'),
        stdin=open(os.devnull),
        )

-- 
 \         “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\         Brain, but how will we get a pair of Abe Vigoda's pants?” |
_o__)                                           —_Pinky and The Brain_ |
Ben Finney



More information about the Python-list mailing list