pygount
Pygount is a command line tool designed to scan folders for source code files and accurately count the number of source lines of code (SLOC). It leverages the robust `pygments` package to parse source code, allowing it to analyze hundreds of programming languages. Pygount, currently at version 3.2.0, is an actively maintained library with regular updates.
Warnings
- breaking Pygount versions 3.x have removed support for older Python versions. Specifically, Python 3.7 and 3.8 are no longer supported. Ensure your environment uses Python 3.10 or newer.
- gotcha The programmatic API (e.g., `SourceAnalysis`, `ProjectSummary`) is explicitly stated as 'work in progress and subject to change'. Breaking changes to the API might occur in future versions.
- gotcha Pygount automatically excludes certain files and folders from analysis by default. This includes files starting with a dot (`.`), files ending with a tilde (`~`), and folders named `.svn` or starting with a dot (`.`).
- gotcha While robust, pygount can be notably slower than other command-line SLOC counting tools due to its detailed `pygments`-based parsing.
Install
-
pip install pygount
Imports
- SourceAnalysis
from pygount import SourceAnalysis
- ProjectSummary
from pygount import ProjectSummary
Quickstart
import os
from pathlib import Path
from pygount import SourceAnalysis, ProjectSummary
# Create dummy files for demonstration
dummy_dir = Path('./my_project')
dummy_dir.mkdir(exist_ok=True)
(dummy_dir / 'main.py').write_text(
"""# This is a Python file
import sys
def hello(): # Code line
print('Hello, world!') # Code line
# Another comment
"""
)
(dummy_dir / 'README.md').write_text(
"""# My Project
This is a test project.
"""
)
(dummy_dir / '.hidden_file.txt').write_text("should not be counted")
project_summary = ProjectSummary()
# Analyze files in the dummy project directory
for source_path in dummy_dir.rglob('*'):
if source_path.is_file():
try:
source_analysis = SourceAnalysis.from_file(source_path, 'my_project')
project_summary.add(source_analysis)
except UnicodeDecodeError as e:
print(f"Warning: Could not decode {source_path}: {e}")
print("\n--- Analysis Results ---")
for language_summary in project_summary.language_to_language_summary_map.values():
print(language_summary)
# Clean up dummy files
import shutil
shutil.rmtree(dummy_dir)