Python unicode popen或Popen读取unicode时出错

4 投票
1 回答
5015 浏览
提问于 2025-04-16 04:41

我有一个程序,它生成了以下输出:

             ┌───────────────────────┐
             │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。

1 个回答

2

我觉得从控制台运行你的程序应该是没问题的,因为Python可以猜测终端窗口的编码方式(在美国的Windows上是cp437),但是当通过管道运行时,Python会使用默认的ascii编码。你可以试着把你的程序改成对所有的Unicode输出进行明确的编码,比如:

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

这样当你从管道读取时,你可以选择把它decode回Unicode,或者直接打印到终端上。

撰写回答