views:

59

answers:

1

I'm having some trouble handling unicode output from a QProcess. When I run the following example I get ?? instead of 中文. Can anyone tell me how to get the unicode output?

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 I tried running your modified code, but I get an error:

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)
A: 

I've changed your code a little and got the expected output:

byte_array:  hello 中文

unicode:  hello 中文

my changes were:

  1. I added # -- coding: utf-8 -- magic comment (details here)
  2. Removed "u" string declaration from the proc.start call

below is your code with my changes:

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

hope this helps, regards

serge_gubenko
I got an error. I edited my question.
Jesse Aldridge
looks like unicode(byte_array) throws this exception, if you would remove it or comment it out it should work fine, it looks like there is no need for this conversion there anyways as the byte_array is not an 8-bits string anymore.
serge_gubenko
But the output is not '中文', it's a bunch of gibberish.
Jesse Aldridge
can you provide some details on your system, e.g. os I've tested your script on my ubuntu 10.04 without issues, my python version is 2.6.5
serge_gubenko