【问题标题】:For loop: How can I pause it after 100 loops for x seconds? [duplicate]For 循环:如何在 100 次循环后暂停 x 秒? [复制]
【发布时间】:2015-03-02 10:03:58
【问题描述】:

我有以下for loop

for user_id in new_followers:
    try:    
        t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
        print("Sent DM to %d" % (user_id))
        followers_old.add(user_id)

为避免 API 限制,我想在每次发送 100 条直接消息时暂停循环 600 秒。

最好的方法是什么?

【问题讨论】:

  • @vaultah 不是真的。我知道如何让 python 程序休眠,但我的问题是在 X 循环完成后让它休眠。
  • 你可以使用time.sleep(x),这里x的单位是mili sec

标签: python


【解决方案1】:

你可以试试这个:

for i, user_id in enumerate(new_followers):
    try:    
        t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
        print("Sent DM to %d" % (user_id))
        followers_old.add(user_id)
        if (i+1)%100 == 0:
             time.sleep(x) # here x in milisecond

【讨论】:

  • 不过应该​​是== 99。此外,time.sleep 需要几秒钟,而不是几毫秒。
  • i+1 % 100 在大多数语言中不会做你想做的事。 Python在这里不同吗,还是需要parens来覆盖%的优先级?
  • 是的,谢谢你的通知,我错过了
【解决方案2】:

你可以这样做:

import time

count = 0

for user_id in new_followers:
    count +=1 
    if count == 100:
        count = 0
        time.sleep(600)
    try:    
        t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
        print("Sent DM to %d" % (user_id))
        followers_old.add(user_id)

【讨论】:

  • 伙计,在这个问题上我们就像鲨鱼一样!
【解决方案3】:
  1. 在循环中使用 counter,最多计算 100 条消息。
  2. counter == 100时,使用

    from time import sleep
    sleep(AMOUNT_OF_TIME)
    

【讨论】:

    【解决方案4】:

    你可以使用:

    import time
    

    然后

    time.sleep(seconds)
    

    睡觉。您可以在不到一秒的时间内使用浮点数。

    有一点需要注意,如果你这样做,人们可能会恨你。

    【讨论】:

    • 我的问题是关于在 X 循环完成后休眠它。
    猜你喜欢
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多