巧妙使用GithubAction配合Python脚本做多平台博客文章备份同步发布工具(附源码)_(2)_编写GithubAction脚本做定时任务

GithubAction介绍

具体的介绍可以看https://github.com/features/actions,简单的一句话来说就是通过配置一个yml文件执行CI/CD自动任务。
通过配置你可以拥有一个带执行环境的docker服务器,而且完全免费。

最好的资料就是官方的文档https://docs.github.com/en/free-pro-team@latest/actions

新建配置文件

将之前的仓库上传到github上,点开该项目的主页。点开Actions

xxx.png

如果你没有配置过action任务脚本,github会自动判断你的脚本类型推荐你安装的环境的配置。比如我这个直接点击Python application环境即可。

然后你的项目下会多出一个文件和目录:

xxxxxx.png

这个就是配置文件

配置文件字段解析

# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: Python application

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]
jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.8
      uses: actions/setup-python@v2
      with:
        python-version: 3.8
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install flake8 pytest
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Lint with flake8
      run: |
        # stop the build if there are Python syntax errors or undefined names
        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
        # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
        flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics

on:事件触发条件

push:表示是push事件就会触发脚本执行接下配置对应的分支
同理pull_request就是pull_request事件。

额外的可以添加一个定时触发条件,使用cron语法:

schedule:
    - cron: "0 0 * * *"

job:执行任务

build:任务名
runs-on:配置操作系统
github给我们选择的系统很多:

Windows Server 2019 windows-latest 或 windows-2019
Ubuntu 20.04    ubuntu-20.04
Ubuntu 18.04    ubuntu-latest 或 ubuntu-18.04
Ubuntu 16.04    ubuntu-16.04
macOS Big Sur 11.0  macos-11.0
macOS Catalina 10.15    macos-latest 或 macos-10.15

steps:执行任务的步骤

执行的任务就是安装环境 这里就是按步骤安装了python 以及 python测试环境 还有requirements.txt的配置文件

添加运行脚本配置随后同步仓库

run: | 就是打开控制台 随后就是输入命令了

运行main

- name: Run Work
      run: |
        python main.py

commit and push

- name: Auto Commit Push
      run: |
        git config --local user.email "1458476478@qq.com"
        git config --local user.name "huruwo"
        git add .
        git commit -m "update" -a
        git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}
        git push

其中github.actor secrets.GITHUB_TOKEN github.repository就属于仓库变量可以直接使用。

运行并调试

这里手动触发事件可以在action里查看执行日志分析执行结果

QQ截图20201212231131.png

这里有成功和失败的

点击失败的进去查看失败原因:

QQ截图20201212231207.png

可以知道是文件路径的问题,修复后再次上传即可。