2013-10-30 71 views
0

我的分析器功能使用lxml并提供了一个Unicode字符串列表(book_list)。Python unicode问题subprocess.call

将这些字符串连接在一起形成文件名,清理后通过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,这让我困惑,因为理论上不应该让像AOU等任何特殊字符)。
  • 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) 

回答

2

写下来的问题,的发行是明确的:)

  • \xdf是UTF-8的原因之后
  • \xc3\x9f is ISO-8859-1 or 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) 

希望这会救别人头疼!