comment-parser is a Python module designed to extract comments from various source code files. It supports common languages like C, C++, Java, JavaScript, Python, and others, handling both single-line and multi-line comment formats. The library, currently at version 1.2.5, features an active release schedule, with recent updates focusing on setup stability and adding typing information.
pip install comment-parserVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to extract comments from both a string and a temporary file. It uses `extract_comments_from_str` and `extract_comments` by explicitly specifying the MIME type for the code, which is recommended for reliable parsing across different languages. The output for each comment includes its text, line number, and whether it's a multi-line comment.
On OSX/Windows, `pip install python-magic`. On Linux/Unix, install `libmagic` via your system package manager (e.g., `sudo apt-get install libmagic-dev` or `sudo yum install file-devel`) in addition to `pip install comment-parser`. Consider explicitly passing the `mime` argument to `extract_comments` or `extract_comments_from_str` for unsupported types or when autodetection fails.
Always check the return value or handle the `UnsupportedError` exception. If the MIME type is known, pass it explicitly using the `mime` argument (e.g., `mime='text/x-python'`). Refer to the project's `comment_parser.py` source for the definitive list of supported MIME types.
Ensure you are using `pip install comment-parser` and importing `from comment_parser import comment_parser` to use the Python version of the library.
Explicitly provide the `mime` argument (e.g., `comment_parser.extract_comments(filename, mime='text/x-python')`). If the language is genuinely unsupported, consider using a different tool or contributing a parser. Ensure `python-magic` and `libmagic` (for Linux/Unix) are installed if relying on auto-detection.
Install the `python-magic` package: `pip install python-magic`. On Linux/Unix, also ensure the `libmagic` system library is installed (e.g., `sudo apt-get install libmagic-dev` or `sudo yum install file-devel`).