我希望这个脚本每分钟运行一次......
import time
import urllib2
from time import sleep
stocksToPull = str('1101'),str('1102'),str('1201'),str('1216'),str('1227')
def pullData(stock):
try:
fileLine = stock+'.txt'
urlToVisit = 'http://mis.tse.com.tw/data/'+stock+'.csv'
sourceCode = urllib2.urlopen(urlToVisit).read()
splitSource = sourceCode.split('\n')
for everyLine in splitSource:
splitLine = everyLine.split(',')
if len(splitLine)==40:
saveFile = open(fileLine,'a')
everyLine = everyLine.replace('"','')
lineToWrite = everyLine+'\n'
saveFile.write(lineToWrite)
print 'pulled',stock
print 'sleeping.....'
except Exception,e:
print ',main loop',str(e)
for eachStock in stocksToPull:
pullData(eachStock)
while True:
starttime = time.time()
pullData(eachStock)
endtime = time.time()-starttime
sleep(65-endtime)
我运行它,它的工作。它将在第一时间获取每个股票的数据,但是在1分钟之后它只是提取1227的数据,它不会全部拉动所有数据。它看起来像这样:
pulled 1101
sleeping.....
pulled 1102
sleeping.....
pulled 1201
sleeping.....
pulled 1216
sleeping.....
pulled 1227
sleeping.....
pulled 1227
sleeping.....
pulled 1227
sleeping.....
怎么能解决这个问题?我使用python 2.7。
答案 0 :(得分:3)
我认为你真的有意这样做:
while True:
starttime = time.time()
for eachStock in stocksToPull:
pullData(eachStock)
duration = time.time()-starttime
sleep(65-duration)
我假设您正在计算睡眠时间,因为您希望它相隔65秒间隔运行,无论每个股票的pullData()花费多长时间。您可以使用APScheduler使用间隔时间表执行此类操作。他们也有很好的装饰。