1

I want to print all the running processes in my computer. One of my processes is called 哈哈.exe. This is my code:

# -*- coding: utf-8 -*-
import psutil
for proc in psutil.process_iter():
        print proc.name().encode('utf-8')

I get the output ??.exe for the Chinese process. Does someone know how to display the process name correctly?

Hexaholic
  • 3,299
  • 7
  • 30
  • 39
Hila
  • 189
  • 1
  • 13

3 Answers3

0

Maybe try doing a format like this?

import psutil

for proc in psutil.process_iter():
    try:
        pinfo = proc.as_dict(attrs=['name'])
    except psutil.NoSuchProcess:
        pass
    else:
        print pinfo
jape
  • 2,861
  • 2
  • 26
  • 58
0

encode is the wrong method for this: The result of encoding is a binary value, ready to be output to file. What you are thinking of is the decode function, which converts a binary value (back) to a string.

If the string doesn't display properly without encoding (or decoding), then you'll need to figure out which encoding is used, convert the name to a bytestring, and then decode it from the correct type.


Like many languages, Python is starting to conceptualize string handling the right way:

  • textual data has no (true) encoding, or byte-semantics. The interpreter uses whatever encoding it wishes, and presents the user with characters. You have to encode it to send it to file (But, there is a default encoding: UTF-8 or locale would both makes sense, and I believe Python chooses UTF-8 for this.)
  • binary data has no textual representation: You have to explicitly decode it in order to treat it as text, and that forces you to think about which encoding it is in.
jpaugh
  • 6,634
  • 4
  • 38
  • 90
0

Your os is Chinese and run the script in cmd window? You could proc.name().encode('gbk')

Em L
  • 328
  • 1
  • 7
  • What is your local encoding? Where run your script? – Em L Jul 19 '16 at 07:35
  • I tried to run it in cmd and also in the Pycharm ide. My OS is in English. – Hila Jul 19 '16 at 07:43
  • Try to open pycharm -> Perferences, find `File encoding`, change IDE and Project encoding as UTF-8, then run your script. – Em L Jul 19 '16 at 08:37
  • Get file system encoding by `sys.getfilesystemencoding()`, for example `GBK` , `print proc.name().decode('GBK').encode('utf-8')`. OR change pycharm encoding as GBK, `print proc.name()` – Em L Jul 19 '16 at 09:08
  • Thanks for the help but I still get the same output :( – Hila Jul 19 '16 at 09:24