我正在尝试从给定目录(包括子目录)运行脚本并检查它们的执行时间。
当涉及到声明很少函数的脚本时,除了主函数之外,我为每个函数得到 NameError: name %method_name% is not defined
。
这是我运行脚本的方式:
def run_scripts(path):
subdirs = os.listdir(path)
for subdir in subdirs:
print('folder ' + subdir)
files = os.listdir(path+'/'+subdir)
for file in files:
print(os.path.dirname(file))
if file.endswith('py'):
print('script \"' + os.path.basename(file) + '\"')
print("output ", end='')
start_time = time.time()
exec(open(path+'/'+subdir+'/'+file, encoding='utf-8').read())
print("time: %s seconds" % (time.time() - start_time))
这是引发 NameError 的可执行脚本的一部分:
filename = 'wiki.txt'
def letters_only(s):
s = s.strip()
for c in s:
if not ((c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or c == ' '):
s = s.replace(c, '')
return s
def count_words(s):
result = {}
words = s.split()
for w in words:
if w in result.keys():
result[w] += 1
else:
result[w] = 1
return result
# other methods...
# main function
def wiki_function():
f = open('wiki.txt', 'r', encoding='utf-8')
data = f.readlines()
for line in data:
print(line)
non_empty = []
for line in data:
if (line != '') and (line != '\n'):
non_empty.append(letters_only(line)) # NameError
text = ' '.join(non_empty)
word_freq = count_words(text) # NameError
# ...
if __name__ == '__main__':
wiki_function()
我应该怎么做才能使功能正常工作?