我正在使用以下代码,该代码在具有类似命名约定的各种文本文件的字符串内容中定义字典中的变量:
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模块使用并行处理同时提交多个URL。我只是在这里使用我的一个定义字典值来测试代码但是我收到以下错误:
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
谁能看到我做错了什么?
答案 0 :(得分:0)
您应该return
来自myglob
的变量:
def myglob():
global myurls2 # Also, never do global declarations. Ever.
return [myurls2[1,1]]
然后我们可以在调用该函数时获取该值,尽管您似乎从未在代码中调用它:
URLS = myglob()
然而值得注意的是,该功能毫无意义,因为它不需要参数 - 更不用说它永远不会被调用。我认为在函数之外(在URLS = [myurls2[1,1]]
语句中)执行with
会使事情变得更简单。