Problems with "Tarfile.close()"

Peter Otten __peter__ at web.de
Fri Dec 20 14:12:11 EST 2019


Dr Rainer Woitok wrote:

> Ethan,
> 
> On Friday, 2019-12-20 07:41:51 -0800, you wrote:
> 
>> ...
>> In Python 3 `sys.stdout` is a character interface, not bytes.
> 
> Does that mean that with Python  3 "Tarfile" is  no longer able to write
> the "tar" file  to a pipe?   Or is there now  another way  to write to a
> pipe?   And if that new way also  worked with Python  2, it would be even
> better ... :-)
> 
>> There are a couple solutions to the Python 3 aspect of the problem here:
>> 
>>    https://stackoverflow.com/q/908331/208880
> 
> Using "sys.stdout.buffer"  seems to work  in Python 3  (at least with my
> current rather trivial test case) but does not work in Python 2.  Quest-
> ion: what is the cheapest way  to retrieve the Python version the script
> is executing in?

While I didn't look into the stackoverflow page an easy way to get something 
that accepts bytes may be

# untested
stdout = sys.stdout
try:
    stdout = stdout.buffer
except AttributeError:
    pass

tarfile.open(fileobj=stdout, ...)



More information about the Python-list mailing list