Sonar Scanner for Python (pysonar)

1.4.0.4676 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

To quickly get started, install `pysonar`, configure your project (ideally via a `[tool.sonar]` section in `pyproject.toml`), and then run the `pysonar` command with your SonarQube or SonarCloud authentication token. The token can be passed via command-line argument `--token` or an environment variable `SONAR_TOKEN`.

# 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!")

view raw JSON →