如何在Google Cloud Platform中定时执行处理.txt文件的Python脚本
需求:在GCP中每30分钟定时执行Python脚本
我需要全天每30分钟执行一次Python脚本,相关文件信息如下:
inputFile.txt 内容
Forecast Today's high: 45 degrees
convert.py 代码
# Conversion code # Open and read the file after the appending: resultFile = open("output.html", "w") # Open the Template file with open('inputFile.txt') as templateFile: templateCode = templateFile.readlines() resultFile.write('<h1>') resultFile.write(templateCode[0]) resultFile.write('</h1>') resultFile.write('\n') resultFile.write('\n') resultFile.write('<p>') resultFile.write(templateCode[2]) resultFile.write('</p>') # Close the Result File resultFile.close() templateFile.close()
运行后生成的 output.html 内容
<h1>Forecast </h1> <p>Today's high: 45 degrees </p>
该脚本可在GCP Cloud Shell中运行,本地能通过Cron定时执行,但我在GCP里尝试了Cloud Scheduler、Cloud Functions、Cloud Run等服务,没法像服务器Cron那样整合实现定时执行。
实现方案:GCP Cloud Scheduler + Cloud Run
这是最贴近传统Cron体验的落地方案,步骤如下:
1. 制作代码容器镜像
- 将
convert.py、inputFile.txt放在同一目录下,创建Dockerfile:
FROM python:3.9-slim WORKDIR /app COPY convert.py inputFile.txt ./ CMD ["python", "convert.py"]
- 构建镜像并推送到GCP Artifact Registry(或Container Registry):
- 配置GCR镜像仓库认证:
gcloud auth configure-docker - 构建镜像:
docker build -t gcr.io/[你的GCP项目ID]/converter:v1 . - 推送镜像:
docker push gcr.io/[你的GCP项目ID]/converter:v1
- 配置GCR镜像仓库认证:
2. 部署Cloud Run服务
- 用刚才的镜像部署Cloud Run服务:
gcloud run deploy converter-service \ --image gcr.io/[你的GCP项目ID]/converter:v1 \ --platform managed \ --region [你的GCP区域,比如us-central1] \ --allow-unauthenticated
- 部署完成后,记录下服务的访问URL(格式类似
https://converter-service-xxxxxx-uc.a.run.app)
3. 配置Cloud Scheduler定时任务
- 创建每30分钟触发一次的Cron任务:
gcloud scheduler jobs create http converter-cron \ --schedule "*/30 * * * *" \ --uri [你的Cloud Run服务URL] \ --http-method GET \ --region [你的GCP区域]
- 其中
*/30 * * * *是标准Cron表达式,代表全天每30分钟执行一次。
4. 持久化输出文件(可选)
如果需要保存生成的output.html,可以修改convert.py,将文件上传到Cloud Storage:
- 安装GCS客户端库:
pip install google-cloud-storage - 修改脚本新增上传逻辑:
# 新增导入 from google.cloud import storage # ... 原有生成output.html的代码 ... # 上传到Cloud Storage storage_client = storage.Client() bucket = storage_client.bucket("[你的Cloud Storage存储桶名称]") blob = bucket.blob("output.html") blob.upload_from_filename("output.html")
- 给Cloud Run服务关联的服务账号添加存储桶的写入权限。
内容的提问来源于stack exchange,提问作者Troy Sidle
相关产品推荐
相关产品推荐

