2010-06-19 103 views
1

我在处理来自QProcess的unicode输出时遇到了一些麻烦。当我运行下面的例子时,我得到了?而不是中文。任何人都可以告诉我如何获得unicode输出?通过QProcess打印unicode

from PyQt4.QtCore import * 

def on_ready_stdout(): 
    byte_array = proc.readAllStandardOutput() 
    print 'byte_array: ', byte_array 
    print 'unicode: ', unicode(byte_array) 

proc = QProcess() 
proc.connect(proc, SIGNAL('readyReadStandardOutput()'), on_ready_stdout) 
proc.start(u'python -c "print \'hello 中文\'"') 
proc.waitForFinished() 

@serge 我试图运行修改后的代码,但我得到一个错误:

byte_array: hello Σ╕¡µ?? 

unicode: 
Traceback (most recent call last): 
    File "python_temp.py", line 7, in on_ready_stdout 
    print 'unicode: ', unicode(byte_array) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 6: ordinal 
not in range(128) 
+0

是您的程序文件的文件格式,目前UTF-8? – 2010-09-06 19:46:55

+0

是的。 _____________________ – 2010-09-06 19:57:07

回答

0

我已经改变了你的代码一点,得到了预期的输出:

byte_array: hello 中文 

unicode: hello 中文 

我的变化是:

  1. 我加了# - - 编码:UTF-8 - - 魔法评论(详情here
  2. 删除了 “U” 的字符串从proc.start呼叫声明
下面

是我改变你的代码:

# -*- coding: utf-8 -*- 
from PyQt4.QtCore import * 

def on_ready_stdout(): 
    byte_array = proc.readAllStandardOutput() 
    print 'byte_array: ', byte_array 
    print 'unicode: ', unicode(byte_array) 

proc = QProcess() 
proc.connect(proc, SIGNAL('readyReadStandardOutput()'), on_ready_stdout) 
proc.start('python -c "print \'hello 中文\'"') 
proc.waitForFinished() 

希望这会有所帮助,至于

+0

我得到了一个错误。我编辑了我的问题。 – 2010-09-06 19:30:15

+0

看起来像unicode(byte_array)会抛出这个异常,如果你删除它或者注释掉它应该可以正常工作,看起来没有必要进行这种转换,因为byte_array不再是8位字符串。 – 2010-09-06 20:28:23

+0

但输出不是'中文',这是一堆乱码。您可以在您的系统上提供一些详细信息,例如 – 2010-09-06 22:41:25