如何让Python等待Power Automate Flow执行完成或获取完成通知
解决Python等待Power Automate Flow执行完成的两种方案
方案一:Python轮询查询Flow执行状态
Power Automate触发后的响应通常会包含状态查询链接(一般在响应的Location头部或响应体中),你可以通过定期请求这个链接,直到Flow执行完成。
具体步骤:
- 触发Flow时,保存响应里的状态查询URL
- 设置轮询间隔(比如每5秒一次),重复向状态URL发送GET请求
- 根据返回的状态字段判断Flow是否结束(比如状态为
Succeeded/Failed/Cancelled)
示例代码:
import requests import time flow0_url = 'url_to_trigger_pa_flow' # 触发Flow response = requests.post(flow0_url) response.raise_for_status() # 获取状态查询URL(通常在Location头部) status_url = response.headers.get('Location') if not status_url: raise ValueError("响应中未找到状态查询URL") # 轮询状态 while True: status_response = requests.get(status_url) status_data = status_response.json() # 根据实际返回的状态字段判断,示例字段为status current_status = status_data.get('status') print(f"当前Flow状态:{current_status}") if current_status in ['Succeeded', 'Failed', 'Cancelled']: print(f"Flow执行完成,状态:{current_status}") if current_status == 'Succeeded': print("Flow执行成功,结果:", status_data.get('outputs')) break # 等待5秒后再次查询 time.sleep(5)
方案二:Power Automate完成后主动回调Python服务
如果你的Python程序能提供公网可访问的API接口,可以让Flow执行完成后主动发送请求通知Python,这种方式比轮询更高效。
具体步骤:
- 用Flask/FastAPI搭建简单的Python Web服务,提供回调接口
- 在Power Automate Flow的最后一步添加「HTTP请求」动作,向回调接口发送完成通知(可携带执行结果)
- Python服务收到回调后,处理Flow的执行结果
示例代码:
Python Web服务(Flask示例):
from flask import Flask, request import threading import time app = Flask(__name__) flow_completed = False flow_result = None @app.route('/flow-callback', methods=['POST']) def flow_callback(): global flow_completed, flow_result flow_result = request.json flow_completed = True return {"status": "received"}, 200 def wait_for_flow(): global flow_completed, flow_result while not flow_completed: time.sleep(1) print("Flow执行完成,结果:", flow_result) if __name__ == '__main__': # 启动等待线程 threading.Thread(target=wait_for_flow).start() # 启动Flask服务(需公网可访问,可使用内网穿透工具如ngrok) app.run(host='0.0.0.0', port=5000)
Power Automate配置:
在Flow的最后一步添加「HTTP」动作,方法选POST,URL填写你的回调接口地址(比如http://你的公网IP:5000/flow-callback),请求体携带执行结果(例如{"status": "Succeeded", "outputs": "@{body('上一步骤名称')}"})。
内容的提问来源于stack exchange,提问作者euh
相关产品推荐
相关产品推荐

