我正在从我在Linux中运行的命令的输出中创建一个字典。
import sys, subprocess, os, string
mycmd = '/usr/bin/mycmd'
myDict = {}
def make_dict(cmd=mycmd):
get_list_cmd = subprocess.Popen('{cmd} get list'.format(cmd=cmd), stdout=subprocess.PIPE)
output, err = get_list_cmd.communicate()
for i in output.splitlines():
detail=i.split(":")
myDict[detail[0].strip()]=detail[1].strip()
make_dict()
当我运行此操作时,我收到以下错误:TypeError: a bytes-like object is required, not 'str'
。
下面是我使用print(output.split())
而不试图将其放入字典时命令的输出:
[b'Serial#', b':', b'xxx00', b'LV', b':',
b'0', b'SL', b':', b'0', b'CL', b':', b'0',
etc..]
如何在每个项目之前移除'b'
?
答案 0 :(得分:1)
例如,你有list
这样:
a = [b'Serial#', b':', b'xxx00', b'LV', b':',b'0', b'SL', b':', b'0', b'CL', b':', b'0']
您需要将其解码为例如utf8
:
c = [k.decode("utf8") for k in a]
输出:
print(c)
>>> ['Serial#', ':', 'xxx00', 'LV', ':', '0', 'SL', ':', '0', 'CL', ':', '0']