以下是config.py:
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
我正在另一个文件 test.py 中使用该函数:
import config
a = config.test_config('test.txt')
NameError: global name 'collections' is not defined
但如果我将整个代码从 config.py 复制粘贴到 test.py 的顶部,然后使用该函数,那么我没有错误(请参见下面的代码)。有人可以向我解释一下吗?我很困惑。非常感谢你!
"""
This is test.py
"""
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
a = test_config('test.txt')
最佳答案
将 from collections import OrderedDict
更改为 import collections
。
关于即使我导入了集合,也没有定义 python 全局名称 'collections',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031880/