python - 在500 HTTP服务器错误后重试,从文件中使用的最后一行继续

标签 python http loops error-handling line

我创建了一个代码,可以从列表中为用户广告,请参见下文;

with open('test.txt') as f:
    for line in f:
        username, password, textfile = line.split(':')
        s.login(username, password)
    file = open(textfile.rstrip('\n'), 'r')         
    for line in file:
        s.add_friend(line) 
        print "Added: " + line,
        print "To account: " + username
        print "Sleeping for:",
        randomtime = random.uniform(.5, 1)
        print randomtime,
        print "seconds"
        time.sleep(randomtime)
    randomtime2 = random.uniform(300, 600)
    print "Timeout till next account, waiting: "
    print randomtime2,
    print "seconds"
    time.sleep(randomtime2)

问题出在这里,我无礼地收到了500http错误代码。
如果我可以使用重试的系统,但又不需要重新开始,那将很酷。
因此,需要以添加的姓氏开头。

名称在文件中的行中。
像这样:
USN1
USN2
USN3
USN4
USN5

因此,让我们在此处创建一个方案:(在命令提示符下)
The user USN1 is added!
The user USN2 is added!
The user USN3 is added!
requests.exceptions.HTTPError 500http error code

我希望脚本现在执行的操作如下:

重试并从USN3重新开始结束。

像这样:
The user USN1 is added!
The user USN2 is added!
The user USN3 is added!
requests.exceptions.HTTPError 500http error code
The user USN3 is added!
The user USN4 is added!
The user USN5 is added!
etc...

有没有办法保存当前所在的行,然后从该位置重试?

我在想,只要添加列表中的每个用户名,我就可以删除它,然后在重试时重新启动文件。
但这似乎有点像贫民窟的解决方案,并不是我真正想要的。

我想知道是否有人知道解决方案,因为我当然不知道,而且我已经寻找了一个多小时。

感恩节快乐,在此先感谢任何可以帮助我的人! :D

最佳答案

为什么不:

with open('test.txt') as f:
    for line in f:
        username, password, textfile = line.split(':')
        s.login(username, password)
    file = open(textfile.rstrip('\n'), 'r')         
    for line in file:
        ok = False
        while not ok:
            try:
                s.add_friend(line) 
                ok = True
            except:
                time.sleep(1)
        print "Added: " + line,
        print "To account: " + username
        print "Sleeping for:",
        randomtime = random.uniform(.5, 1)
        print randomtime,
        print "seconds"
        time.sleep(randomtime)
    randomtime2 = random.uniform(300, 600)
    print "Timeout till next account, waiting: "
    print randomtime2,
    print "seconds"
    time.sleep(randomtime2)

关于python - 在500 HTTP服务器错误后重试,从文件中使用的最后一行继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27190401/

相关文章:

python - Matplotlib 2.0 中不同的 Figsize 定义

python - 为什么 Python 返回 [15] for [0xfor x in (1, 2, 3)]?

asp.net-mvc-3 - HTTP 请求的内容长度 > 正文大小

r - 在R中的特定时间暂停特定时间的循环

c - C中的无限循环

python - 在 Python 中使用 GdkPixbuf.Pixbuf.savev() 的正确语法是什么?

python - pandas 将列转为行

http - 有没有监控HTTP响应的工具?

javascript - 链接多个Node http请求

c - 从长度为 k 的 n 个数中生成递增子序列