2

我在处理来自 QProcess 的 unicode 输出时遇到了一些问题。当我运行以下示例时,我得到 ?? 而不是中文。谁能告诉我如何获得 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)
4

1 回答 1

0

我稍微更改了您的代码并获得了预期的输出:

byte_array:  hello 中文

unicode:  hello 中文

我的改变是:

  1. 我添加了 # - - coding: utf-8 - - 魔术注释(详情请点击此处
  2. 从 proc.start 调用中删除了“u”字符串声明

以下是您的代码以及我的更改:

# -*- 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()

希望这会有所帮助,问候

于 2010-09-06T02:48:57.913 回答