简体   繁体   English

S3 文件到本地使用 luigi 引发 UnicodeDecodeError

[英]S3 file to local using luigi raises UnicodeDecodeError

I am copying a pdf file to local, using the following piece of code:我正在使用以下代码将pdf文件复制到本地:

with self.input_target().open('r') as r:
    with self.output_target().open('w') as w:
       for line in r: 
           w.write(line) 

Which is based in this question (kind of)这是基于这个问题(种类)

But when I execute that code I get the following:但是当我执行该代码时,我得到以下信息:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 11:
      invalid continuation byte

I tried this other approach, without good results:我尝试了另一种方法,但没有很好的结果:

   with self.input_target().open('r') as r, self.output_target().open('w') as w:                                                                                                                        
       w.write(r.read())                         

What is the correct way of doing it?正确的做法是什么?

It seems that you're dealing with a binary file as if it was text - but it's not.似乎您正在处理一个二进制文件,就好像它是文本一样 - 但事实并非如此。 You probably need to do something like this:你可能需要做这样的事情:

with self.input().open('r') as i, self.output().open('w') as o:
    o.write(i.read())

(not tested!) (未测试!)

Also, I think you may find this answer useful: Python writing binary files, bytes另外,我认为您可能会发现这个答案很有用: Python 编写二进制文件,字节

I ended using luigi.s3.S3Client and the method get which copies a binary file from/to the s3 .我结束了使用luigi.s3.S3Client和从/向s3复制二进制文件的方法get

Snippet of code:代码片段:

import luigi进口路易吉

class ATask(luigi.Task):
    s3_path = luigi.Parameter()
    local_path = luigi.Parameter()
    ...

    def run(self):
        client = luigi.s3.S3Client()
        client.get(s3_path, local_path)  ## This gets the file
        ...

I think that the underlying reason is that luigi uses boto for getting/putting files from/to the s3 .我认为根本原因是luigi使用boto从/向s3获取/放置文件。 (As you can see in the source code) (如您在源代码中所见)

Another option would be to use the format kwarg luigi.format.Nop to Target to indicate that it is a binary file that is being read.另一种选择是使用格式 kwarg luigi.format.Nop 到 Target 来指示它是一个正在读取的二进制文件。

eg例如

def output(self):
    return LocalTarget(target, format=luigi.format.Nop)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM