Sonar Scanner for Python (pysonar)
pysonar is a command-line tool developed by SonarSource for static code analysis of Python projects with SonarQube or SonarCloud. It acts as a wrapper around the SonarScanner CLI, simplifying configuration and execution for Python ecosystems. It is actively maintained with frequent releases, currently at version 1.4.0.4676, and supports configuration via `pyproject.toml` or `sonar-project.properties` files.
Common errors
-
command not found: pysonar
cause `pysonar` executable is not in your system's PATH after installation, or pip's script directory is not included in PATH.fixEnsure `pip install pysonar` completed successfully. Verify that the directory where pip installs scripts (e.g., `~/.local/bin` on Linux/macOS, or `Scripts` subdirectory of your Python installation on Windows) is included in your system's PATH environment variable. -
ERROR: Could not find a JRE. Please set the SONAR_SCANNER_OPTS environment variable or download and install a JRE.
cause pysonar, as a wrapper around the SonarScanner CLI, requires a Java Runtime Environment (JRE) to execute. It attempts to provision one, but can fail in certain environments.fixInstall a JRE (Java 11 or higher recommended, ensure it's on your PATH) or manually set the `SONAR_SCANNER_OPTS` environment variable to point to your JRE's `bin` directory or specify a `sonar.java.home` property. pysonar versions 1.0+ include JRE provisioning, so ensure you have a recent version. -
You are trying to scan a project with an analysis key '...' that is already being scanned by the SonarScanner CLI.
cause Conflicting analysis attempts for the same project key, possibly due to both `pysonar` and the generic `sonar-scanner` CLI being used, or an outdated `sonar-project.properties` file conflicting with `pyproject.toml` configuration.fixEnsure you are consistently using only `pysonar` for Python projects and that project keys are unique. Prioritize configuration via `pyproject.toml` under `[tool.sonar]`. Check for and remove any conflicting `sonar-project.properties` files if `pyproject.toml` is the intended source of truth. -
ERROR: Error during SonarQube Scanner execution. ERROR: Please provide the value for the 'sonar.projectKey' property.
cause The required `sonar.projectKey` property was not provided via CLI, `pyproject.toml`, or `sonar-project.properties` file.fixDefine `project-key` (or `projectKey`) under `[tool.sonar]` in your `pyproject.toml` file, or pass `-Dsonar.projectKey=YourProjectKey` via the command line. Ensure the file is in the current directory or its path is specified correctly if not.
Warnings
- breaking The `pysonar-scanner` PyPI package is deprecated in favor of `pysonar`. Users should migrate to `pysonar` for all new projects and existing projects where possible. The deprecated package is no longer actively maintained and may break.
- gotcha pysonar requires SonarQube Server v10.6 or higher, or SonarCloud. Older versions of pysonar (before 1.0.1) incorrectly stated compatibility with SonarQube v9.9. If you are on an older SonarQube server, you might need to use the deprecated `pysonar-scanner` or upgrade your SonarQube instance.
- gotcha When defining SonarQube analysis properties in a `pyproject.toml` file under `[tool.sonar]`, the `sonar.` prefix for property keys should be omitted. Property keys are generally camelCase (e.g., `projectKey`), although kebab-case is also accepted (e.g., `project-key`).
- gotcha pysonar is a wrapper around the SonarScanner CLI. While it simplifies Python project analysis, it still fundamentally relies on the underlying SonarScanner CLI. This means some deep troubleshooting might involve understanding the generic SonarScanner CLI behavior.
Install
-
pip install pysonar
Imports
- pysonar
import pysonar
pysonar --help
Quickstart
# 1. Install pysonar
pip install pysonar
# 2. Configure your project (e.g., in pyproject.toml in your project root)
# Replace <your-project-key> with your SonarQube project key.
# For SonarCloud, also uncomment and set 'organization'.
# For SonarQube Server, ensure host.url is set if not default.
#
# [tool.sonar]
# project-key = "<your-project-key>"
# # host.url = "https://sonarqube.example.com"
# # organization = "<your-organization-key>"
# 3. Run the analysis
# Ensure SONAR_TOKEN is set in your environment with a valid SonarQube/SonarCloud token.
# Example: export SONAR_TOKEN="your_sonar_token_here"
import os
sonar_token = os.environ.get('SONAR_TOKEN', '')
if not sonar_token:
print("Error: SONAR_TOKEN environment variable not set. Please set it before running pysonar.")
else:
print("Running SonarQube analysis...")
# The actual command would be run in your shell or CI/CD pipeline
# For demonstration, we'll print it. In a real scenario, you'd use subprocess.run()
print(f"Executing: pysonar --token {sonar_token}")
# Example of actual command to run (requires `pysonar` to be in PATH):
# import subprocess
# result = subprocess.run(["pysonar", "--token", sonar_token], capture_output=True, text=True)
# print(result.stdout)
# if result.stderr: print(result.stderr)
# if result.returncode != 0: print("Analysis failed!")