Python如何编程在一定时间后关闭
Python How to Program to be Closed After a Certain Time
这个问题有点傻,但我对编码非常陌生。我无法将我在互联网上找到的解决方案添加到我的代码中。如果你能帮上忙,我会很高兴。
当我打开.py文件时,程序没有自动停止。它 运行 直到我关闭命令 window。打开此文件后,我希望它 运行 持续 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
您可以监控您程序的运行时间,在时间限制后打破for-loop。
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
这个问题有点傻,但我对编码非常陌生。我无法将我在互联网上找到的解决方案添加到我的代码中。如果你能帮上忙,我会很高兴。
当我打开.py文件时,程序没有自动停止。它 运行 直到我关闭命令 window。打开此文件后,我希望它 运行 持续 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
您可以监控您程序的运行时间,在时间限制后打破for-loop。
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