Search code examples
pythonwindowscontinuous-integrationgithub-actions

How to save python script output in GitHub Actions running on windows-latest?


I have the following GitHub Actions Workflow:

name: Workflow
on: [push]

permissions:
  id-token: write
  contents: read

jobs:
  workflow:
    runs-on: windows-latest
    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          ...

      - name: Run code
        id: exit_code
        run: |
          $result = python test/test_1.py
          echo "my_output=$result" >> "$GITHUB_OUTPUT"

      - name: Check Output and Fail if Not Equal to 0
        shell: bash
        run: |
          output_value="${{ steps.exit_code.outputs.my_output }}"
          if [[ "$output_value" != "0" ]]; then
            echo "Output value is not 0. Failing the action."
            exit 1
          else
            echo "Output value is 0. Continuing with the action."
          fi

The script runs as expected and I would like to save its output inside GitHub Actions so that I can check it in the last step. The script returns an int with the output_value between 0 and 4. I would like to fail the workflow if the output_value != 0.

I get the error that the value that's given to the next step is just an empty string instead of the number I'm expecting:

Run if [[ "" -ne "0" ]]; then
  if [[ "" -ne "0" ]]; then
    echo "Output value is not 0. Failing the action."
    exit 1
  else
    echo "Output value is 0. Continuing with the action."
  fi
  shell: C:\Program Files\Git\bin\bash.EXE --noprofile --norc -e -o pipefail {0}

Here is how the python file looks:

...

def test():
    ...

    return exit_code


if __name__ == "__main__":
    exit_code_final = test()
    print(exit_code_final)

I've also tried this, based on another answer:

...

def test():
    ...

    return exit_code


if __name__ == "__main__":
    print(test())

Solution

  • Because this is windows the syntax is: $env:GITHUB_OUTPUT and not just $GITHUB_OUTPUT.

    So change it here:

    - name: Run code
      id: exit_code
      run: |
        $result = python test/test_1.py
        echo "my_output=$result" >> "$env:GITHUB_OUTPUT"