GitHub Cron Job运行Python Requests脚本跳过循环无预期输出求助
问题排查与解决步骤
- 先排查最常见的依赖缺失问题:GitHub Ubuntu 运行器的默认Python环境没有预装
requests库,你当前的工作流配置里没有安装依赖的步骤,脚本运行时直接触发ImportError就终止执行,是导致10秒快速结束、没有执行核心逻辑的最常见原因。
你需要修改工作流的Main步骤,在运行脚本前安装依赖:
更规范的做法是在仓库根目录创建- name: Main run: | pip3 install requests python3 ./scripts/test.pyrequirements.txt写入requests==2.31.0,工作流里执行pip3 install -r requirements.txt即可。 - 补充Python脚本的异常捕获和状态校验:你当前的代码没有对API请求做任何错误判断,GitHub运行器的出口IP很容易被目标API拦截返回403/404等错误,直接调用
.json()会触发异常终止脚本。同时你原请求头里的^\^转义符在Linux环境下解析规则和Windows不同,会导致请求头格式错误触发API拦截,需要修正。
修改后的核心循环参考代码:import requests import traceback headers = { 'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99"', 'Referer': 'https://www.a.com/', 'sec-ch-ua-mobile': '?0', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36', } genres = ['Hindi%20News','Hindi%20Entertainment','Music','Entertainment','Movie','Movies','Lifestyle'] params = { 'sort_by_field': 'channel_number', 'sort_order': 'ASC', 'genres': '', 'country': 'IN', 'translation': 'en', 'languages': 'hi', } channels = [] for genre in genres: print(f'正在处理分类:{genre}') params['genres'] = genre try: # 加超时参数,防止请求无限卡住 resp = requests.get('https://xxxxxxx/v1/channel/bygenre', headers=headers, params=params, timeout=10) # 先校验响应状态码 resp.raise_for_status() a_channel_list = resp.json() except Exception as e: # 打印错误信息,方便在Actions日志里排查 print(f'请求分类接口失败,错误信息:{str(e)}') print(traceback.format_exc()) continue # 校验返回结构是否符合预期 if not a_channel_list.get('items') or not a_channel_list['items'][0].get('items'): print(f'分类{genre}返回数据为空,跳过') continue for a_channel in a_channel_list['items'][0]['items']: id = a_channel['id'] api_url = "https://yyyyyy/?url={}".format(id) try: resp = requests.get(api_url, timeout=10) resp.raise_for_status() url_content = resp.text except Exception as e: print(f'请求频道{id}接口失败,错误信息:{str(e)}') continue if a_channel['genres'][0]['value'] == 'Hindi News': a_cat = 'News' elif a_channel['genres'][0]['value'] == 'Hindi Entertainment': a_cat = 'Entertainment' else: a_cat = a_channel['genres'][0]['value'] channel = { 'title': a_channel['title'], 'category': a_cat, 'language': a_channel['languages'][0], 'url': url_content} channels.append(channel) # 最后打印处理结果,确认逻辑执行完成 print(f'全部处理完成,共获取{len(channels)}个频道数据') - 校验Git提交逻辑:如果你的脚本最终要把生成的文件写入仓库,要注意如果没有文件变更,
git commit步骤会报错终止工作流,你可以修改提交步骤的代码,先判断是否有变更再提交:- name: commit & push run: | git diff --quiet && git diff --staged --quiet || (git commit -m "updated" && git push) - 手动触发工作流排查日志:修改完代码后,进入仓库的Actions tab,找到对应的工作流,点击
Run workflow手动触发运行,点开执行记录的每一步就能看到详细的输出日志,根据报错信息就能精确定位问题。
内容的提问来源于stack exchange,提问作者raman singh
相关产品推荐
相关产品推荐

