首页 > 解决方案 > 解析元组时出现ValueError?

问题描述

我的剧本是——

import subprocess
z = subprocess.check_output(['python3', 'test1.py'],universal_newlines=True)
mas = z
mas = dict(mas)
e = mas.get('email')
print(e)

我得到一个错误-

ValueError: dictionary update sequence element #0 has length 1; 2 is required

但是当我跑——

mas = {'email': 'something@gmail.com'}
mas = dict(mas)
e = mas.get('email')
print(e)

我得到了所需的输出,即something@gmail.com. 此外,的输出test1.py{'email': 'something@gmail.com'}

标签: pythonpython-3.xparsingtuples

解决方案


check_output()将进程输出作为字符串返回。如果你知道它代表一个 Python 字典,你可以使用ast.literal_eval()

import ast
import subprocess

z = subprocess.check_output(['python3', 'test1.py'], universal_newlines=True)
mas = ast.literal_eval(z)

也就是说,我宁愿将 python 文件作为模块导入并直接使用其中的函数。


推荐阅读