更改一个真正的python脚本只运行一次

问题描述 投票:0回答:1

我是python的新手,我希望这段代码只运行一次并停止,而不是每隔30秒

因为我希望使用命令行每隔5秒运行不同访问令牌的多个代码。当我尝试这个代码时,它永远不会跳到第二个,因为它有一段时间是真的:

import requests
import time

api_url = "https://graph.facebook.com/v2.9/"
access_token = "access token"
graph_url = "site url"
post_data = { 'id':graph_url, 'scrape':True, 'access_token':access_token }
# Beware of rate limiting if trying to increase frequency.
refresh_rate = 30 # refresh rate in second

while True:
    try:
        resp = requests.post(api_url, data = post_data)
        if resp.status_code == 200:
            contents = resp.json()
            print(contents['title'])
        else:
            error = "Warning: Status Code {}\n{}\n".format(
                resp.status_code, resp.content)
            print(error)
            raise RuntimeWarning(error)
    except Exception as e:
        f = open ("open_graph_refresher.log", "a")
        f.write("{} : {}".format(type(e), e))
        f.close()
        print(e)
    time.sleep(refresh_rate)
python facebook-graph-api
1个回答
0
投票

据我所知,你正试图执行多个访问令牌的代码。为了简化您的工作,请将所有access_tokens作为列表并使用以下代码。它假设您事先知道所有access_tokens

import requests
import time

def scrape_facebook(api_url, access_token, graph_url):
    """ Scrapes the given access token"""
    post_data = { 'id':graph_url, 'scrape':True, 'access_token':access_token }

    try:
        resp = requests.post(api_url, data = post_data)
        if resp.status_code == 200:
            contents = resp.json()
            print(contents['title'])
        else:
            error = "Warning: Status Code {}\n{}\n".format(
                resp.status_code, resp.content)
            print(error)
            raise RuntimeWarning(error)
    except Exception as e:
        f = open (access_token+"_"+"open_graph_refresher.log", "a")
        f.write("{} : {}".format(type(e), e))
        f.close()
        print(e)

access_token = ['a','b','c']
graph_url = ['sss','xxx','ppp']
api_url = "https://graph.facebook.com/v2.9/"

for n in range(len(graph_url)):
    scrape_facebook(api_url, access_token[n], graph_url[n])
    time.sleep(5)
© www.soinside.com 2019 - 2024. All rights reserved.