Problem with subprocess module on Windows with open file in append mode

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Oct 6 01:30:08 EDT 2009


En Sat, 03 Oct 2009 21:53:12 -0300, Andrew Savige <ajsavige at yahoo.com.au>  
escribió:

> When I run this little test program on Linux:
>
> import subprocess
> subprocess.call(["python","-V"], stderr=open("log.tmp","a"))
>
> the file log.tmp is appended to each time I run it.
> When I run it on Windows, however, the file log.tmp gets
> overwritten each time I run it.
>
> Though I can make it append on Windows like this:
>
> import os
> import subprocess
> f = open("log.tmp", "a")
> f.seek(0, os.SEEK_END)
> subprocess.call(["python","-V"], stderr=f)
>
> I don't understand why that should be necessary.
>
> Is this a Python/subprocess bug on Windows?

No, it's an "implementation-defined behavior" of the underlying C library.  
 From the C89 standard:

"""4.9.3 Files

[...] If a
file can support positioning requests (such as a disk file, as opposed
to a terminal), then a file position indicator associated with
the stream is positioned at the start (character number zero) of the
file, unless the file is opened with append mode in which case it is
implementation-defined whether the file position indicator is
positioned at the beginning or the end of the file."""

The Linux implementation choose to move the file pointer to the end in  
such cases, the Windows one choose to always keep it at the start. Both  
are correct according to the specification above. Python 2.X just inherits  
that behavior from C. If you want to write portable code, you'll have to  
use the longer form.

-- 
Gabriel Genellina




More information about the Python-list mailing list