我有一个脚本可以告诉我的笔记本电脑还剩多少电量。如果可能的话,我想要一个适用于 python 2 和 python 3 的通用解决方案。通过我自己的修修补补,我似乎只能通过电缆让 python 2 或 python 3 工作。这是代码:
#battery.py
#!/usr/bin/env python
# coding=UTF-8
import math
import subprocess
p = subprocess.Popen(["ioreg", "-rc", "AppleSmartBattery"], stdout=subprocess.PIPE)
output = p.communicate()[0]
o_max = [l for l in output.splitlines() if b'MaxCapacity' in l][0]
o_cur = [l for l in output.splitlines() if b'CurrentCapacity' in l][0]
b_max = float(o_max.rpartition(b'=')[-1].strip())
b_cur = float(o_cur.rpartition(b'=')[-1].strip())
charge = b_cur / b_max
charge_threshold = int(math.ceil(10 * charge))
# Output
total_slots, slots = 10, []
filled = int(math.ceil(charge_threshold * (total_slots / 10.0))) * u"\u25CF"
empty = (total_slots - len(filled)) * u"\u25CB"
#out = (filled + empty).decode('utf-8')
out = u' '.join((filled, empty)).encode('utf8').strip()
import sys
color_green = '%{[32m%}'
color_yellow = '%{[1;33m%}'
color_red = '%{[31m%}'
color_reset = '%{[00m%}'
color_out = (
color_green if len(filled) > 6
else color_yellow if len(filled) > 3
else color_red
)
# out = color_out + out + color_reset #works with py2
out = color_out + out.decode('utf-8','ignore') + color_reset #works with py3
sys.stdout.write(out)
当运行 python exectubales python 和 python3 时,脚本会按预期提供输出:
$ python batcharge.py
%{%}●●●●●●●●●●%{%}%
$ python3 batcharge.py
%{%}●●●●●●●●●●%{%}%
然而,当 shell 调用文件以在我的提示中显示其输出时,我从 python2 收到一个回溯错误:
Traceback (most recent call last):
File "/usr/local/bin/batcharge.py", line 40, in <module>
sys.stdout.write(out)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-18: ordinal not in range(128)
当我使用带有 python3 作为默认 python 的 virtualenv 时,它工作正常。请帮忙。
请您参考如下方法:
我使用使用 try/except 子句的大杂烩解决方案让它同时与 python2 和 python3 一起工作。在这里,我尝试使用 python 2 代码,如果它抛出异常,我使用 python3 代码:
try: #python 2 code, throws TypeError in python 3
out = color_out + out + color_reset
except TypeError: #python 3 code
out = color_out + out.decode('utf-8','ignore') + color_reset
finally:
sys.stdout.write(out)
它非常不优雅,最终不是 pythonic,IMO。我愿意接受更优雅的解决方案。
