Write a GitHub Action in Python
GitHub Actions allow you to automate your software development workflows in the same place where you store your code. Here's how you can write a GitHub Action in Python:
Create a new workflow: Workflows are defined in the
.github/workflowsdirectory of your repository. To create a new workflow, add a new file with a.ymlextension to this directory.Define the steps of your workflow: Workflows are made up of a series of steps that are executed in order. Each step is defined using a
- name:line followed by a series ofrun:lines that specify the command to be executed.Use the
actions/checkoutaction to checkout your code: The first step of your workflow should be to checkout your code so that it can be used in the subsequent steps. You can do this using theactions/checkoutaction.Install dependencies: If your code depends on any packages, you'll need to install them before you can use them. You can use the
pipcommand to install the packages listed in yourrequirements.txtfile.Run your tests: You can use the
pythoncommand to run your tests. For example, if your tests are located in atestsdirectory, you can run them using the following command:python -m unittest discover tests.
Here's an example of a simple Python workflow that checks out the code, installs dependencies, and runs tests:
name: Python application
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install dependencies
run: |
pip install -r requirements.txt
- name: Run tests
run: |
python -m unittest discover tests
This workflow listens for pushes to the main branch, checks out the code, sets up a Python 3.8 environment, installs dependencies, and runs tests.





