首页 > 解决方案 > 如何在循环中运行函数,从文件中逐行提取参数

问题描述

我正在编写一个脚本,该脚本将 url、用户名和密码作为参数,发出 Web 请求并记录结果。我想使用一个包含许多站点/凭据的 csv 文件,并循环每个条目的请求,如果有任何异常/错误,我只想跳到文件中的下一个条目,但我的脚本在第一次运行后挂起循环

目前我只是通过命令行标志手动传递参数,但这不可行,因为手动执行需要很长时间当我尝试创建循环并从文件中提取参数时,我的函数运行一次然后挂起无限期地,无论是否存在例外,都会发生这种情况。

#currently Im using command line arguments to manually input the 
#arguments for the function below, which works fine but I want to pull 
#arguments from a list in a csv file (see comments at end for what ive #tried)


def webrequest(username,password):
 url = site
    headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
               'Accept-Encoding' : 'none'
    }
    payload = {'log': username,
               'pwd': password
               }
    session = requests.session
    r = session.post(url, headers=headers, data=payload)
    if r.status_code == 404
        print "404"
        #end function, move on to next line in csv
    if r.status_code == 200
        print r.text
        # move on to next line in csv



#file = open(file, r)
#with open(file) as f:
#    for line in f:
#       args = line.split(",")
#       webrequest(args[0],args[1],args[2])

我希望当函数到达末尾时使用 csv 文件中的下一行重新开始,但它没有......它只是挂在命令行

标签: python

解决方案


使用 timeout 参数尝试 session.post()。详细信息:http: //docs.python-requests.org/en/master/user/advanced/#timeouts

很可能您的 Web 服务器没有返回响应,所以您觉得您的功能被卡住了。


推荐阅读