【问题标题】:Python unicode issue with subprocess.callsubprocess.call 的 Python unicode 问题
【发布时间】:2013-10-30 18:40:42
【问题描述】:

我的解析器函数使用 lxml 并为我提供了 unicode 字符串列表 (book_list)。

这些字符串被合并成一个文件名,被清理,然后通过subprocess.call 传递给另一个继续工作的二进制文件。

我的问题是 unicode 对象(例如title_name = u'Wunderlicher Traum von einem gro\xdfen Narrennest')是用 ISO-8859-2 编码的(至少 'chardet' 是这样告诉我的),我需要将它们转换为一种格式,该格式可以正确显示在文件系统级别。当前代码导致文件名为u'Wunderlicher Traum von einem gro\xc3\x9fen Narrennest'

有人知道我做错了什么吗?

一些信息:

  • sys.getdefaultencoding() 返回 ascii,这让我很困惑,因为理论上不应该允许任何特殊字符,如 äöü 等)。
  • OS X 10.9,Python 2.7.5

def convert_books(book_list, output_dir):
    for book in book_list:
        author_name = book[0][0]
        title_name = book[0][1]
        #print chardet.detect(title_name)
        #print type(title_name)
        #print title_name.decode('iso-8859-2')
        year_name = "1337"

        output_file = u"%s - %s (%s).pdf" % (author_name, title_name, year_name)
        keep_characters = (' ', '.', '_')
        output_file.join(c for c in output_file if c.isalnum() or c in keep_characters).rstrip()
        path_to_out = "%s%s" % (output_dir, output_file)

        target_file = WORK_DIR + book[1].replace(".xml", ".html")

        engine_parameter = [
            WKHTMLTOPDF_BIN,

            # GENERAL
            "-l", # lower quality
            "-L", "25mm",
            "-R", "25mm",
            "-T", "25mm",
            "-B", "35mm",
            "--user-style-sheet", "media/style.css",

            target_file,
            path_to_out,
        ]
        print "+ Creating PDF \"%s\"" % (output_file)
        call(engine_parameter)

【问题讨论】:

    标签: python unicode subprocess python-unicode


    【解决方案1】:

    写下问题后,发出的原因就清楚了:)

    • \xdf 是 UTF-8
    • \xc3\x9f是 ISO-8859-1 或 latin-1

    我所要做的就是将 utf-8 对象转换为 latin-1 对象,然后将参数传递给 subprocess.call。

    out_enc = 'latin-1'
    engine_parameter = [arg.encode(out_enc) if isinstance(arg, unicode) else arg for arg in engine_parameter]
    call(engine_parameter)
    

    希望这可以避免其他人的头痛!

    【讨论】:

      猜你喜欢
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2011-02-05
      • 1970-01-01
      • 2013-03-21
      • 2015-07-07
      相关资源
      最近更新 更多