仅将 while true python 脚本更改为 运行 一次

Change a while true python script to run only once

我是 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)

据我了解,您正在尝试执行用于多个访问令牌的代码段。为了简化您的工作,将所有 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)