我正在运行一个子流程:packets = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
并收集输出。它返回stdout = {'port2_tx': 1000L, 'port2_rx': 1000L, 'port1_rx': 1000L, 'port1_tx': 1000L}\n
编辑:此子进程是python2工具(不可转换为3)
我想将其转换为字典并获取:
Traceback (most recent call last):
File "robot/lib/libraries/WarpTrafficLib.py", line 31, in <module>
send_warp_traffic('172.18.0.48','***','***', _create_streams_arg(stream), 10)
File "robot/lib/libraries/WarpTrafficLib.py", line 19, in send_warp_traffic
return dict(out.strip())
TypeError: cannot convert dictionary update sequence element #0 to a sequence
>>> x
b"{'port2_tx': 1000L, 'port2_rx': 1000L, 'port1_rx': 1000L, 'port1_tx': 1000L}"
>>> ast.literal_eval(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 85, in literal_eval
return _convert(node_or_string)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 84, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: b"{'port2_tx': 1000L, 'port2_rx': 1000L, 'port1_rx': 1000L, 'port1_tx': 1000L}"
>>> import json
>>> d = json.loads(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
尝试过json
和ast.literal_eval
在将其加载为字典之前,是否需要从字符串中剥离L
还是有更好的方法?
答案 0 :(得分:0)
因此,以下代码在Python 3中失败:
>>> 1L
1L
>>> long(1)
1L
如果确实需要它,则可以在不进行2to3转换的情况下在Python 2和Python 3上使用:
>>> import sys
>>> if sys.version_info > (3,):
... long = int
>>> long(1)
1L
对于我所要解决的问题,
x = b"{'port2_tx': 1000L, 'port2_rx': 1000L, 'port1_rx': 1000L, 'port1_tx': 1000L}"
x = x.replace(b'L',b'')
ast.literal_eval(x.decode('utf-8'))
{'port2_tx': 1000, 'port2_rx': 1000, 'port1_rx': 1000, 'port1_tx': 1000}