{"meta":{"title":"Создание и тестирование Python","intro":"Узнайте, как создать рабочий процесс непрерывной интеграции (CI) для создания и тестирования вашего проекта на Python.","product":"GitHub Actions","breadcrumbs":[{"href":"/ru/enterprise-cloud@latest/actions","title":"GitHub Actions"},{"href":"/ru/enterprise-cloud@latest/actions/tutorials","title":"Учебники"},{"href":"/ru/enterprise-cloud@latest/actions/tutorials/build-and-test-code","title":"Сборка и тестирование кода"},{"href":"/ru/enterprise-cloud@latest/actions/tutorials/build-and-test-code/python","title":"Python"}],"documentType":"article"},"body":"# Создание и тестирование Python\n\nУзнайте, как создать рабочий процесс непрерывной интеграции (CI) для создания и тестирования вашего проекта на Python.\n\n<!-- TRANSLATION_FALLBACK prop=markdown type=ParseError line=450 col=1 msg=\"tag 'endraw' not found\" -->\n## Introduction\n\nThis guide shows you how to build, test, and publish a Python package.\n\nGitHub-hosted runners have a tools cache with pre-installed software, which includes Python and PyPy. You don't have to install anything! For a full list of up-to-date software and the pre-installed versions of Python and PyPy, see [GitHub-hosted runners](/en/enterprise-cloud@latest/actions/using-github-hosted-runners/about-github-hosted-runners#supported-software).\n\n## Prerequisites\n\nYou should be familiar with YAML and the syntax for GitHub Actions. For more information, see [Writing workflows](/en/enterprise-cloud@latest/actions/learn-github-actions).\n\nWe recommend that you have a basic understanding of Python, and pip. For more information, see:\n\n* [Getting started with Python](https://www.python.org/about/gettingstarted/)\n* [Pip package manager](https://pypi.org/project/pip/)\n\n## Using a Python workflow template\n\nTo get started quickly, add a workflow template to the `.github/workflows` directory of your repository.\n\nGitHub provides a workflow template for Python that should work if your repository already contains at least one `.py` file. The subsequent sections of this guide give examples of how you can customize this workflow template.\n\n1. On GitHub, navigate to the main page of the repository.\n\n2. Under your repository name, click **<svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-play\" aria-label=\"play\" role=\"img\"><path d=\"M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z\"></path></svg> Actions**.\n\n   ![Screenshot of the tabs for the \"github/docs\" repository. The \"Actions\" tab is highlighted with an orange outline.](/assets/images/help/repository/actions-tab-global-nav-update.png)\n\n3. If you already have a workflow in your repository, click **New workflow**.\n\n4. The \"Choose a workflow\" page shows a selection of recommended workflow templates. Search for \"Python application\".\n\n5. On the \"Python application\" workflow, click **Configure**.\n\n6. Edit the workflow as required. For example, change the Python version.\n\n7. Click **Commit changes**.\n\n   The `python-app.yml` workflow file is added to the `.github/workflows` directory of your repository.\n\n## Specifying a Python version\n\nTo use a pre-installed version of Python or PyPy on a GitHub-hosted runner, use the `setup-python` action. This action finds a specific version of Python or PyPy from the tools cache on each runner and adds the necessary binaries to `PATH`, which persists for the rest of the job. If a specific version of Python is not pre-installed in the tools cache, the `setup-python` action will download and set up the appropriate version from the [`python-versions`](https://github.com/actions/python-versions) repository.\n\nUsing the `setup-python` action is the recommended way of using Python with GitHub Actions because it ensures consistent behavior across different runners and different versions of Python. If you are using a self-hosted runner, you must install Python and add it to `PATH`. For more information, see the [`setup-python` action](https://github.com/marketplace/actions/setup-python).\n\nThe table below describes the locations for the tools cache in each GitHub-hosted runner.\n\n<div class=\"ghd-tool rowheaders\">\n\n|                          | Ubuntu                          | Mac                                      | Windows                               |\n| ------------------------ | ------------------------------- | ---------------------------------------- | ------------------------------------- |\n| **Tool Cache Directory** | `/opt/hostedtoolcache/*`        | `/Users/runner/hostedtoolcache/*`        | `C:\\hostedtoolcache\\windows\\*`        |\n| **Python Tool Cache**    | `/opt/hostedtoolcache/Python/*` | `/Users/runner/hostedtoolcache/Python/*` | `C:\\hostedtoolcache\\windows\\Python\\*` |\n| **PyPy Tool Cache**      | `/opt/hostedtoolcache/PyPy/*`   | `/Users/runner/hostedtoolcache/PyPy/*`   | `C:\\hostedtoolcache\\windows\\PyPy\\*`   |\n\n</div>\n\nIf you are using a self-hosted runner, you can configure the runner to use the `setup-python` action to manage your dependencies. For more information, see [using setup-python with a self-hosted runner](https://github.com/actions/setup-python#using-setup-python-with-a-self-hosted-runner) in the `setup-python` README.\n\nGitHub supports semantic versioning syntax. For more information, see [Using semantic versioning](https://docs.npmjs.com/about-semantic-versioning#using-semantic-versioning-to-specify-update-types-your-package-can-accept) and the [Semantic versioning specification](https://semver.org/).\n\n### Using multiple Python versions\n\nThe following example uses a matrix for the job to set up multiple Python versions. For more information, see [Running variations of jobs in a workflow](/en/enterprise-cloud@latest/actions/using-jobs/using-a-matrix-for-your-jobs).\n\n```yaml copy\nname: Python package\n\non: [push]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: [\"pypy3.10\", \"3.9\", \"3.10\", \"3.11\", \"3.12\", \"3.13\"]\n\n    steps:\n      - uses: actions/checkout@v5\n      - name: Set up Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v5\n        with:\n          python-version: ${{ matrix.python-version }}\n      # You can test your matrix by printing the current Python version\n      - name: Display Python version\n        run: python -c \"import sys; print(sys.version)\"\n```\n\n### Using a specific Python version\n\nYou can configure a specific version of Python. For example, 3.12. Alternatively, you can use semantic version syntax to get the latest minor release. This example uses the latest minor release of Python 3.\n\n```yaml copy\nname: Python package\n\non: [push]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v5\n      - name: Set up Python\n        # This is the version of the action for setting up Python, not the Python version.\n        uses: actions/setup-python@v5\n        with:\n          # Semantic version range syntax or exact version of a Python version\n          python-version: '3.x'\n          # Optional - x64 or x86 architecture, defaults to x64\n          architecture: 'x64'\n      # You can test your matrix by printing the current Python version\n      - name: Display Python version\n        run: python -c \"import sys; print(sys.version)\"\n```\n\n### Excluding a version\n\nIf you specify a version of Python that is not available, `setup-python` fails with an error such as: `##[error]Version 3.7 with arch x64 not found`. The error message includes the available versions.\n\nYou can also use the `exclude` keyword in your workflow if there is a configuration of Python that you do not wish to run. For more information, see [Workflow syntax for GitHub Actions](/en/enterprise-cloud@latest/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstrategy).\n\n```yaml copy\nname: Python package\n\non: [push]\n\njobs:\n  build:\n\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        os: [ubuntu-latest, macos-latest, windows-latest]\n        python-version: [\"3.9\", \"3.11\", \"3.13\", \"pypy3.10\"]\n        exclude:\n          - os: macos-latest\n            python-version: \"3.11\"\n          - os: windows-latest\n            python-version: \"3.11\"\n```\n\n### Using the default Python version\n\nWe recommend using `setup-python` to configure the version of Python used in your workflows because it helps make your dependencies explicit. If you don't use `setup-python`, the default version of Python set in `PATH` is used in any shell when you call `python`. The default version of Python varies between GitHub-hosted runners, which may cause unexpected changes or use an older version than expected.\n\n| GitHub-hosted runner | Description                                                                                                                                                                                                                                                                                                                     |\n| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Ubuntu               | Ubuntu runners have multiple versions of system Python installed under `/usr/bin/python` and `/usr/bin/python3`. The Python versions that come packaged with Ubuntu are in addition to the versions that GitHub installs in the tools cache.                                                                                    |\n| Windows              | Excluding the versions of Python that are in the tools cache, Windows does not ship with an equivalent version of system Python. To maintain consistent behavior with other runners and to allow Python to be used out-of-the-box without the `setup-python` action, GitHub adds a few versions from the tools cache to `PATH`. |\n| macOS                | The macOS runners have more than one version of system Python installed, in addition to the versions that are part of the tools cache. The system Python versions are located in the `/usr/local/Cellar/python/*` directory.                                                                                                    |\n\n## Installing dependencies\n\nGitHub-hosted runners have the pip package manager installed. You can use pip to install dependencies from the PyPI package registry before building and testing your code. For example, the YAML below installs or upgrades the `pip` package installer and the `setuptools` and `wheel` packages.\n\nYou can also cache dependencies to speed up your workflow. For more information, see [Dependency caching reference](/en/enterprise-cloud@latest/actions/using-workflows/caching-dependencies-to-speed-up-workflows).\n\n```yaml copy\nsteps:\n- uses: actions/checkout@v5\n- name: Set up Python\n  uses: actions/setup-python@v5\n  with:\n    python-version: '3.x'\n- name: Install dependencies\n  run: python -m pip install --upgrade pip setuptools wheel\n```\n\n### Requirements file\n\nAfter you update `pip`, a typical next step is to install dependencies from `requirements.txt`. For more information, see [pip](https://pip.pypa.io/en/stable/cli/pip_install/#example-requirements-file).\n\n```yaml copy\nsteps:\n- uses: actions/checkout@v5\n- name: Set up Python\n  uses: actions/setup-python@v5\n  with:\n    python-version: '3.x'\n- name: Install dependencies\n  run: |\n    python -m pip install --upgrade pip\n    pip install -r requirements.txt\n```\n\n### Caching Dependencies\n\nYou can cache and restore the dependencies using the [`setup-python` action](https://github.com/actions/setup-python).\n\nThe following example caches dependencies for pip.\n\n```yaml copy\nsteps:\n- uses: actions/checkout@v5\n- uses: actions/setup-python@v5\n  with:\n    python-version: '3.12'\n    cache: 'pip'\n- run: pip install -r requirements.txt\n- run: pip test\n```\n\nBy default, the `setup-python` action searches for the dependency file (`requirements.txt` for pip, `Pipfile.lock` for pipenv or `poetry.lock` for poetry) in the whole repository. For more information, see [Caching packages dependencies](https://github.com/actions/setup-python#caching-packages-dependencies) in the `setup-python` README.\n\nIf you have a custom requirement or need finer controls for caching, you can use the [`cache` action](https://github.com/marketplace/actions/cache). Pip caches dependencies in different locations, depending on the operating system of the runner. The path you'll need to cache may differ from the Ubuntu example above, depending on the operating system you use. For more information, see [Python caching examples](https://github.com/actions/cache/blob/main/examples.md#python---pip) in the `cache` action repository.\n\n## Testing your code\n\nYou can use the same commands that you use locally to build and test your code.\n\n### Testing with pytest and pytest-cov\n\nThis example installs or upgrades `pytest` and `pytest-cov`. Tests are then run and output in JUnit format while code coverage results are output in Cobertura. For more information, see [JUnit](https://junit.org/junit5/) and [Cobertura](https://cobertura.github.io/cobertura/).\n\n```yaml copy\nsteps:\n- uses: actions/checkout@v5\n- name: Set up Python\n  uses: actions/setup-python@v5\n  with:\n    python-version: '3.x'\n- name: Install dependencies\n  run: |\n    python -m pip install --upgrade pip\n    pip install -r requirements.txt\n- name: Test with pytest\n  run: |\n    pip install pytest pytest-cov\n    pytest tests.py --doctest-modules --junitxml=junit/test-results.xml --cov=com --cov-report=xml --cov-report=html\n```\n\n### Using Ruff to lint and/or format code\n\nThe following example installs or upgrades `ruff` and uses it to lint all files. For more information, see [Ruff](https://docs.astral.sh/ruff).\n\n```yaml copy\nsteps:\n- uses: actions/checkout@v5\n- name: Set up Python\n  uses: actions/setup-python@v5\n  with:\n    python-version: '3.x'\n- name: Install the code linting and formatting tool Ruff\n  run: pipx install ruff\n- name: Lint code with Ruff\n  run: ruff check --output-format=github --target-version=py39\n- name: Check code formatting with Ruff\n  run: ruff format --diff --target-version=py39\n  continue-on-error: true\n```\n\nThe formatting step has `continue-on-error: true` set. This will keep the workflow from failing if the formatting step doesn't succeed. Once you've addressed all of the formatting errors, you can remove this option so the workflow will catch new issues.\n\n### Running tests with tox\n\nWith GitHub Actions, you can run tests with tox and spread the work across multiple jobs. You'll need to invoke tox using the `-e py` option to choose the version of Python in your `PATH`, rather than specifying a specific version. For more information, see [tox](https://tox.readthedocs.io/en/latest/).\n\n```yaml copy\nname: Python package\n\non: [push]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python: [\"3.9\", \"3.11\", \"3.13\"]\n\n    steps:\n      - uses: actions/checkout@v5\n      - name: Setup Python\n        uses: actions/setup-python@v5\n        with:\n          python-version: ${{ matrix.python }}\n      - name: Install tox and any other packages\n        run: pip install tox\n      - name: Run tox\n        # Run tox using the version of Python in `PATH`\n        run: tox -e py\n```\n\n## Packaging workflow data as artifacts\n\nYou can upload artifacts to view after a workflow completes. For example, you may need to save log files, core dumps, test results, or screenshots. For more information, see [Store and share data with workflow artifacts](/en/enterprise-cloud@latest/actions/using-workflows/storing-workflow-data-as-artifacts).\n\nThe following example demonstrates how you can use the `upload-artifact` action to archive test results from running `pytest`. For more information, see the [`upload-artifact` action](https://github.com/actions/upload-artifact).\n\n```yaml copy\nname: Python package\n\non: [push]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: [\"3.9\", \"3.10\", \"3.11\", \"3.12\", \"3.13\"]\n\n    steps:\n      - uses: actions/checkout@v5\n      - name: Setup Python # Set Python version\n        uses: actions/setup-python@v5\n        with:\n          python-version: ${{ matrix.python-version }}\n      # Install pip and pytest\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip\n          pip install pytest\n      - name: Test with pytest\n        run: pytest tests.py --doctest-modules --junitxml=junit/test-results-${{ matrix.python-version }}.xml\n      - name: Upload pytest test results\n        uses: actions/upload-artifact@v4\n        with:\n          name: pytest-results-${{ matrix.python-version }}\n          path: junit/test-results-${{ matrix.python-version }}.xml\n        # Use always() to always run this step to publish test results when there are test failures\n        if: ${{ always() }}\n```\n\n## Publishing to PyPI\n\nYou can configure your workflow to publish your Python package to PyPI once your CI tests pass. This section demonstrates how you can use GitHub Actions to upload your package to PyPI each time you publish a release. For more information, see [Managing releases in a repository](/en/enterprise-cloud@latest/repositories/releasing-projects-on-github/managing-releases-in-a-repository).\n\nThe example workflow below uses [Trusted Publishing](https://docs.pypi.org/trusted-publishers/) to authenticate with PyPI, eliminating the need for a manually configured API token.\n\n```yaml copy\n# This workflow uses actions that are not certified by GitHub.\n# They are provided by a third-party and are governed by\n# separate terms of service, privacy policy, and support\n# documentation.\n\n# GitHub recommends pinning actions to a commit SHA.\n# To get a newer version, you will need to update the SHA.\n# You can also reference a tag or branch, but the action may change without warning.\n\nname: Upload Python Package\n\non:\n  release:\n    types: [published]\n\npermissions:\n  contents: read\n\njobs:\n  release-build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v5\n\n      - uses: actions/setup-python@v5\n        with:\n          python-version: \"3.x\"\n\n      - name: Build release distributions\n        run: |\n          # NOTE: put your own distribution build steps here.\n          python -m pip install build\n          python -m build\n\n      - name: Upload distributions\n        uses: actions/upload-artifact@v4\n        with:\n          name: release-dists\n          path: dist/\n\n  pypi-publish:\n    runs-on: ubuntu-latest\n\n    needs:\n      - release-build\n\n    permissions:\n      # IMPORTANT: this permission is mandatory for trusted publishing\n      id-token: write\n\n    # Dedicated environments with protections for publishing are strongly recommended.\n    environment:\n      name: pypi\n      # OPTIONAL: uncomment and update to include your PyPI project URL in the deployment status:\n      # url: https://pypi.org/p/YOURPROJECT\n\n    steps:\n      - name: Retrieve release distributions\n        uses: actions/download-artifact@v5\n        with:\n          name: release-dists\n          path: dist/\n\n      - name: Publish release distributions to PyPI\n        uses: pypa/gh-action-pypi-publish@6f7e8d9c0b1a2c3d4e5f6a7b8c9d0e1f2a3b4c5d\n```\n\nFor more information about this workflow, including the PyPI settings\nneeded, see [Configuring OpenID Connect in PyPI](/en/enterprise-cloud@latest/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-pypi)."}