我收到此错误"主循环' builtin_function_or_method'对象不可迭代"当我运行以下代码时:
我有搜索stackoverflow,但无法找到我的问题的答案...
我已检查过拼写错误,但无法找到任何错误。请帮帮我!
import urllib2
import time
import datetime
stocksToPull = 'AAPL','GOOG','MSFT','CMG','AMZN','EBAY','TSLA'
def pullData(stock):
try:
print 'Currently pulling',stock
print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=5d/csv'
saveFileLine = stock+'.txt'
try:
readExistingData = open(saveFileLine,'r').read()
splitExisting = readExistingData.split('\n')
mostRecentLine = splitExisting[-2]
lastUnix = mostRecentLine.split(',')[0]
except:
lastUnix = 0
saveFile = open(saveFileLine,'a')
sourceCode = urllib2.urlopen(urlToVisit).read()
splitSource = sourceCode.split
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine) ==6:
if splitLine[0] > lastUnix:
if 'values' not in eachLine:
lineToWrite = eachLine+'\n'
saveFile.write(lineToWrite)
saveFile.close()
print 'Pulled',stock
print 'sleeping...'
print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
time.sleep(300)
except Exception,e:
print 'main loop',str(e)
for eachStock in stocksToPull:
pullData(eachStock)
答案 0 :(得分:6)
直接回答
在这里的代码中:
saveFile = open(saveFileLine,'a')
sourceCode = urllib2.urlopen(urlToVisit).read()
splitSource = sourceCode.split
将sourceCode.split
更改为sourceCode.split()
。
如果您想了解有关此错误的更多信息,请阅读以下内容:
调试时,你最好删除try ... except块,特别是"期待异常"阻止,这是如此通用,你会迷失方向。
当删除try ... except块并再次运行这些代码时,您将收到如下错误信息:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-c4fe20f718cd> in <module>()
43
44 for eachStock in stocksToPull:
---> 45 pullData(eachStock)
<ipython-input-5-c4fe20f718cd> in pullData(stock)
23 splitSource = sourceCode.split
24
---> 25 for eachLine in splitSource:
26 splitLine = eachLine.split(',')
27 if len(splitLine) ==6:
TypeError: 'builtin_function_or_method' object is not iterable
错误消息TypeError: 'builtin_function_or_method' object is not iterable
与第25行相关联,这意味着splitSource
为builtin_function_or_method
且不是iterable
。
什么是splitSource
?它是sourceCode.split
。答案就是这样。您应该使用()
调用方法,否则您将获得方法本身。方法str.split
显然不是iterable
!