为什么我会收到变量未定义的错误?
我正在使用以下代码,这段代码是从一些命名方式相似的文本文件中提取字符串内容,并在一个字典里定义变量:
import concurrent.futures
import urllib.request
import json
myurls2 = {}
for x in range(1, 15):
for y in range(1, 87):
strvar1 = "%s" % (x)
strvar2 = "%s" % (y)
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f:
myurls2[x,y] = f.read().replace('\n', '')
#print("myurls_" + str(strvar1) + "_" + str(strvar2) + "=", myurls[x,y])
#print(myurls2[x,y])
def myglob():
global myurls2
URLS = [myurls2[1,1]]
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
concurrent.futures
是一个 Python 模块,它可以让你同时处理多个网址,也就是并行处理。我在这里只是用我定义的字典中的一个值来测试代码,但我遇到了以下错误:
Traceback (most recent call last):
File "C:\Python33\test2.py", line 35, in <module>
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
NameError: name 'URLS' is not defined
有人能帮我看看我哪里出错了吗?
1 个回答
0
你只需要从 myglob
中 return
这个变量:
def myglob():
global myurls2 # Also, never do global declarations. Ever.
return [myurls2[1,1]]
这样我们在调用这个函数的时候就可以得到这个值,不过在你的代码里似乎从来没有调用过这个函数:
URLS = myglob()
不过值得注意的是,这个函数其实没什么用,因为它没有接收任何参数,更别提它根本没有被调用。我觉得直接在你的 with
语句外面写 URLS = [myurls2[1,1]]
会简单很多。