如何在GitHub Workflow触发push事件时运行Python文件?
问题根源
GitHub Actions中每个job默认运行在完全独立的全新虚拟机实例上,不同job之间的环境、文件不会共享。你的sending-email任务没有执行仓库代码拉取操作,所以运行器的工作目录里根本不存在send_email.py文件,就会触发找不到文件的报错。
解决步骤
- 给
sending-email任务添加上拉取仓库代码的步骤,和你第一个任务里的拉取代码步骤一致即可,建议将旧版的actions/checkout@v2升级到更稳定的最新v4版本 - 可选:如果你的Python脚本有第三方依赖,还需要补充设置Python环境、安装依赖的步骤
修改后的完整workflow代码如下:
name: GitHub Actions Demo on: [push] jobs: Explore-GitHub-Actions: runs-on: ubuntu-latest steps: - run: echo "🎉 The job was automatically triggered by a ${{ github.event_name }} event." - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by GitHub!" - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." - name: Check out repository code uses: actions/checkout@v4 - run: echo "💡 The ${{ github.repository }} repository has been cloned to the runner." - run: echo "🖥️ The workflow is now ready to test your code on the runner." - name: List files in the repository run: | ls ${{ github.workspace }} - run: echo "🍏 This job's status is ${{ job.status }}." sending-email: runs-on: ubuntu-latest steps: # 新增拉取仓库代码的步骤 - name: Check out repository code uses: actions/checkout@v4 # 可选:如果需要指定Python版本、安装依赖,取消注释下面的步骤即可 # - name: Set up Python # uses: actions/setup-python@v5 # with: # python-version: '3.11' # 替换为你实际使用的Python版本 # - name: Install dependencies # run: pip install -r requirements.txt # 存在依赖文件时启用 - name: send email run: | python ./send_email.py
额外排查方案
如果添加拉取代码步骤后依然报错,可以在运行Python脚本前新增目录文件打印步骤,确认文件路径是否匹配:
- name: Check workspace files run: ls -la ${{ github.workspace }}
如果send_email.py不在仓库根目录,将执行路径替换为实际的相对路径即可,比如存放在scripts目录下就修改为python ./scripts/send_email.py。
内容的提问来源于stack exchange,提问作者DolenDeori
相关产品推荐
相关产品推荐

