【问题标题】:Python unicode popen or Popen error reading unicodePython unicode popen 或 Popen 读取 unicode 错误
【发布时间】:2011-04-18 03:22:28
【问题描述】:

我有一个生成以下输出的程序:

             ┌───────────────────────┐
             │10 day weather forecast│
             └───────────────────────┘
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
Tonight Sep 27      Clear               54      0 %
Tue Sep 28          Sunny               85/61   0 %
Wed Sep 29          Sunny               86/62   0 %
Thu Sep 30          Sunny               87/65   0 %
Fri Oct 01          Sunny               85/62   0 %
Sat Oct 02          Sunny               81/59   0 %
Sun Oct 03          Sunny               79/56   0 %
Mon Oct 04          Sunny               78/58   0 %
Tue Oct 05          Sunny               81/61   0 %
Wed Oct 06          Sunny               81/61   0 %

Last Updated Sep 27 10:20 p.m. CT
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

这似乎在这个网站上没有正确的格式,但顶部的下一行和底部的上一行导致 unicode 错误。

这是 os.popen 的代码示例

>>> buffer = popen('10day', 'r').read()
Traceback (most recent call last):
  File "/home/woodnt/python/10_day_forecast.py", line 129, in <module>
    line_lower(51)
  File "/home/woodnt/python/lib/box.py", line 24, in line_lower
    print upper_line * len
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-50: ordinal not in range(128)
>>> print buffer

             ┌───────────────────────┐
             │10 day weather forecast│
             └───────────────────────┘

>>> 

subprocess.Popen 也一样:

f = Popen('10day', stdout=PIPE, stdin=PIPE, stderr=PIPE)
o, er = f.communicate()
print o

             ┌───────────────────────┐
             │10 day weather forecast│
             └───────────────────────┘

print er
Traceback (most recent call last):
  File "/home/woodnt/python/10_day_forecast.py", line 129, in <module>
    line_lower(51)
  File "/home/woodnt/python/lib/box.py", line 24, in line_lower
    print upper_line * len
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-50: ordinal not in range(128)

如果无需大量“幕后”工作就可以实现这一点,有什么想法吗?我只是在学习编程并从python开始

【问题讨论】:

  • 不知道为什么上面的格式如此不正确。我很抱歉。

标签: python shell unicode popen


【解决方案1】:

我想说从控制台运行你的程序应该可以正常工作,因为 Python 可以猜测终端窗口的控制台编码(美国 Windows 上的 cp437),但是当通过管道运行时,Python 使用默认的 ascii。试试把你的程序改成encode所有的Unicode输出到显式编码,比如:

print (upper_line * len).encode('cp437')

然后当你从管道中读取它时,你可以decode 回到 Unicode 或直接打印到终端。

【讨论】:

  • 可悲的是,它确实在控制台上犹豫了。从 python 控制台,只要执行 popen。我认为您对默认为 ascii 的管道很了解。猜想没有办法改变这种行为。太糟糕了。按照你的建议去做是个好主意。我会试一试的。
  • 成功了。感谢您提供出色的解决方法。我想如果这是另一个程序并且我没有源代码并且它是二进制文件,那么就没有办法解决这个问题,嗯?
  • 源程序为Python时,可以在Popen前使用os.environ['PYTHONIOENCODING'] = 'utf-8'。此环境变量指示 python 使用 UTF-8 作为默认值而不是 ASCII。所有 Unicode 字符都可以使用这种编码发送...只需 .decode('utf-8') 接收到的输出转回 Unicode。
猜你喜欢
  • 2016-10-21
  • 1970-01-01
  • 2012-10-31
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 2014-09-29
相关资源
最近更新 更多