尝试延迟运行已定义的函数 [英] Trying to run a defined function with a delay

查看:97
本文介绍了尝试延迟运行已定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图逐步将csv文件第一列的值加载到URL中,并以5秒的延迟一次请求一个URL。

这是我的代码:

 #我有一个定义的函数
def withid(theid):



全局缓存

dupe = False

theurl ={0} {1} {2}。格式(OMDBURL,?i =,theid)

对于缓存中的mov,返回= urllib2.urlopen(theurl)

movdata = json.load(响应)


如果movdata [MKEY [1]] = = mov [MKEY [1]]:
dupe = True
如果不是dupe:
cache.append(movdata)



outfile2 = open('outputrows2-shortened.csv','rb')
for outfile2中的行:
theid = outfile2(row [0])
time.sleep(5)

输出:TypeError:'file'对象不可调用

withid()函数永远不会返回任何内容。尝试在结尾处添加 return movdata



这是一个可能有用的重写版本: p>

 导入csv 
导入json
导入时间
导入urllib2

PAGE_DELAY = 5.#加载页面之间的时间
PAGE_LOAD = 0.3#加载页面需要多长时间

make_url ='http://www.imdb.com/title/tt {格式
$ b $ def get_csv_column(csv_fname,col,** kwargs):
开放(csv_fname,'rb')as inf:
incsv = csv.reader (inf,** kwargs)
column = [row [col] for row in incsv]
return column

def get_data_by_id(id):
url = make_url (id)
response = urllib2.urlopen(url)
data = json.load(响应)
返回id,数据

延迟(延迟,fn, * args):
time.sleep(延迟)
返回fn(* args)

def人工时间(秒):
if seconds> = 86400:
返回'{:0.1f}天'格式(秒/ 86400)
elif seconds> = 3600:
返回'{:0.1f} hours'.format(秒/ 3600.)
elif seconds> = 60:
返回'{:0.1f}分钟'.format(分钟/ 60.)
其他:
返回'{:0.1f}秒'.format(秒)

def main():
ids = get_csv_column('outputrows2.csv',0)

expected =(PAGE_DELAY + PAGE_LOAD)* len(ids)
print('这将需要{}。'format(human_time(expected)))

results =(延迟(PAGE_DELAY,get_data_by_id,id)id中的id)
moviedata = dict(results )#=>如果__name __ ==__ main__:
main()

,则给出{id:data}的字典{bb}:

b $ b

I am trying to incrementally load values from the first column of a csv file into a URL and request the URL one at a time with a 5 second delay. Each value in the first column should replace "theid"

This is my code so far:

 # I have a defined function
 def withid (theid):
    """"""


    global cache

    dupe = False

    theurl = "{0}{1}{2}".format(OMDBURL, "?i=", theid)

    response = urllib2.urlopen(theurl)

    movdata = json.load(response)

    for mov in cache:
        if movdata[MKEY[1]] == mov[MKEY[1]]:
            dupe = True
    if not dupe:
        cache.append(movdata)



outfile2 = open('outputrows2-shortened.csv', 'rb')
for row in outfile2:
  theid = outfile2(row[0])
  time.sleep(5)

output: TypeError: 'file' object is not callable

解决方案

Your withid() function never returns anything. Try adding return movdata at the end of it.

Here is a rewritten version which may be helpful:

import csv
import json
import time
import urllib2

PAGE_DELAY = 5.    # time between loading pages
PAGE_LOAD  = 0.3   # how long it takes to load a page

make_url = 'http://www.imdb.com/title/tt{}/'.format

def get_csv_column(csv_fname, col, **kwargs):
    with open(csv_fname, 'rb') as inf:
        incsv = csv.reader(inf, **kwargs)
        column = [row[col] for row in incsv]
    return column

def get_data_by_id(id):
    url = make_url(id)
    response = urllib2.urlopen(url)
    data = json.load(response)
    return id,data

def delayed(delay, fn, *args):
    time.sleep(delay)
    return fn(*args)

def human_time(seconds):
    if seconds >= 86400:
        return '{:0.1f} days'.format(seconds / 86400.)
    elif seconds >= 3600:
        return '{:0.1f} hours'.format(seconds / 3600.)
    elif seconds >= 60:
        return '{:0.1f} minutes'.format(minutes / 60.)
    else:
        return '{:0.1f} seconds'.format(seconds)

def main():
    ids = get_csv_column('outputrows2.csv', 0)

    expected = (PAGE_DELAY + PAGE_LOAD) * len(ids)
    print('This will take about {}.'.format(human_time(expected)))

    results = (delayed(PAGE_DELAY, get_data_by_id, id) for id in ids)
    moviedata = dict(results)     # => gives dict of {id:data}

if __name__=="__main__":
    main()

这篇关于尝试延迟运行已定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆