如何仅获取Pylint评分值?正则提取是否为唯一方案?
Great question! I’ve wrestled with this exact Pylint limitation before, so I feel your pain.
First, let’s confirm your findings: you’re 100% correct—Pylint doesn’t have a dedicated command-line flag or a straightforward method in epylint.py_run that returns only the numeric score (e.g., 7.5 or 7.5/10). All built-in output modes either dump the full report, or focus on errors/warnings without isolating the final score.
That said, regex extraction from standard output is the most common and straightforward solution, but it’s not strictly the only feasible approach. Here’s a breakdown of your options:
Option 1: Regex Extraction (Quick & Dirty)
Pylint’s final score line follows a consistent format like:
Your code has been rated at 7.50/10 (previous run: 7.20/10, +0.30)
You can easily parse this with regex, either via command-line tools or in Python.
Command-Line Example
pylint <package-to-scan> | grep -oP 'rated at \K[0-9.]+/[0-9]+' # Or to get just the numeric value before the slash: pylint <package-to-scan> | grep -oP 'rated at \K[0-9.]+'
Python Example (Using Subprocess)
import subprocess import re result = subprocess.run( ["pylint", "<package-to-scan>"], capture_output=True, text=True ) score_match = re.search(r"rated at ([0-9.]+)/[0-9]+", result.stdout) if score_match: score = float(score_match.group(1)) print(f"Pylint Score: {score}")
Option 2: Custom Pylint Reporter (Robust, Programmatic)
If you want a more integrated, reliable solution (and don’t mind diving into Pylint’s API), you can create a custom reporter that only tracks and outputs the final score. This avoids relying on parsing stdout, which could break if Pylint changes its output format.
Here’s a minimal example:
from pylint.lint import Run from pylint.reporters.base_reporter import BaseReporter import re class ScoreOnlyReporter(BaseReporter): def __init__(self, output=None): super().__init__(output) self.score = None def display_reports(self, layout): # Extract the score from the global stats section for section in layout.children: if hasattr(section, 'children'): for child in section.children: if hasattr(child, 'data') and 'global_note' in child.data: note_text = child.data['global_note'] score_match = re.search(r"rated at ([0-9.]+)/[0-9]+", note_text) if score_match: self.score = float(score_match.group(1)) # Run Pylint with the custom reporter reporter = ScoreOnlyReporter() Run(["<package-to-scan>"], reporter=reporter) print(f"Pylint Score: {reporter.score}")
Verdict
Regex extraction is the easiest and most widely used approach for most cases. The custom reporter is better if you’re building a tool that relies on Pylint’s score long-term, as it’s less fragile to output changes.
So to answer your question: no, regex extraction isn’t the only feasible solution, but it’s the most practical one for most scenarios.
内容的提问来源于stack exchange,提问作者Dev

