【问题标题】:Python How to Program to be Closed After a Certain TimePython如何编程在一定时间后关闭
【发布时间】:2020-12-29 12:42:26
【问题描述】:

这个问题有点傻,但我对编码非常陌生。我无法将在 Internet 上找到的解决方案添加到我的代码中。如果你能提供帮助,我会很高兴。


当我打开 .py 文件时,程序不会自动停止。它一直运行,直到我关闭命令窗口。打开此文件后,我希望它运行 5 分钟,然后自行关闭。 如何设置关闭程序的时间限制?

import tweepy
import time


auth = tweepy.OAuthHandler('*','*')
auth.set_access_token('*','*')


api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
user = api.me()

search = 'books'
nrTweets = 500


for tweet in tweepy.Cursor(api.search, search).items(nrTweets):

    try: 
        print('Tweet Liked')
        tweet.favorite()

        time.sleep(10)
    except tweepy.TweepError as e:
        print(e.reason)
    except StopIteration:
        break

【问题讨论】:

  • 这是您要找的吗? 12。由于这与线程有关,我认为您不能精确地停在 5 分钟。
  • @HungVu 我猜数字 2 是我的答案。但是,我怎样才能使这段代码适应我的代码?

标签: python time tweepy


【解决方案1】:

你可以监控你的程序的运行时间,并在时间限制后打破for循环。

import time

time_limit_sec = 5 * 60
start_time = time.time()

for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
    if (time.time()-start_time) > time_limit_sec:
        break
    ...  # your code here

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 1970-01-01
    • 2013-09-18
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多