Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
hamdanal committed Dec 31, 2022
0 parents commit 814fcb5
Show file tree
Hide file tree
Showing 18 changed files with 1,456 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[flake8]
max_line_length = 100
extend-select = B950
extend-ignore = E203, E501
per-file-ignores =
lsports/_windows.py: E221, E402
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.coverage
.tox/
*.egg-info/
*.pyc
htmlcov/
venv/
build/
dist/
43 changes: 43 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-added-large-files
- id: check-builtin-literals
- id: check-case-conflict
- id: check-docstring-first
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
- id: mixed-line-ending
args: [--fix=lf]
- id: trailing-whitespace
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/pycqa/isort
rev: 5.11.4
hooks:
- id: isort
args: [--add-import, "from __future__ import annotations"]
- repo: https://github.com/psf/black
rev: 22.12.0
hooks:
- id: black
- repo: https://github.com/asottile/yesqa
rev: v1.4.0
hooks:
- id: yesqa
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies: [ "flake8-bugbear" ]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
hooks:
- id: mypy
47 changes: 47 additions & 0 deletions .vscode/cspell.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
// Version of the setting file. Always 0.2
"version": "0.2",
// language - current active spelling language
"language": "en",
// words - list of words to be always considered correct
"words": [
"amba",
"cdrom",
"cfgmgr",
"devinst",
"devpkey",
"devprop",
"devpropguid",
"devpropid",
"devpropkey",
"devs",
"dics",
"digcf",
"direg",
"fmtid",
"ftdi",
"ftdibus",
"guids",
"hardwareid",
"hdevinfo",
"hwid",
"iokit",
"iousb",
"liechti",
"lpctstr",
"lsports",
"pguid",
"ptstr",
"raspi",
"spdrp",
"sysfs",
"wparam"
],
// flagWords - list of words to be always considered incorrect
// This is useful for offensive words and common spelling errors.
// For example "hte" should be "the"
"flagWords": [
"hte",
"tge"
]
}
12 changes: 12 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"python.formatting.provider": "none",
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
}
57 changes: 57 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
MIT License

Copyright (c) 2022 Ali Hamdan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


-------------------------------------------------------------------------------
Original source: pySerial https://github.com/pyserial/pyserial

Copyright (c) 2001-2020 Chris Liechti <[email protected]>
All Rights Reserved.


Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# lsports

A simple Python 3.7+ module to list serial ports on Windows, Linux, and macOS.

This is a modified version of `serial.tools.list_ports` from
[pySerial](https://github.com/pyserial/pyserial) by Chris Liechti.

## Installation

```bash
pip install lsports
```

## Usage

The module provides a single function `comports` that returns a list of `PortInfo` objects.
Each `PortInfo` object contains information about a connected serial port.
```python
from lsports import comports

for port in comports():
print(port.device, port.product, port.hwid)
```
For a full list of available attributes, see the `PortInfo` class. Only `comports` and `PortInfo`
are considered public API.
17 changes: 17 additions & 0 deletions lsports/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Originally sourced from pySerial. https://github.com/pyserial/pyserial
# (C) 2011-2015 Chris Liechti <[email protected]>
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations

import os

from lsports._common import PortInfo as PortInfo

__all__ = ["comports", "PortInfo"]

if os.name == "nt":
from lsports._windows import comports as comports # type: ignore[attr-defined]
elif os.name == "posix":
from lsports._posix import comports as comports
else:
raise ImportError(f"No implementation available for '{os.name}' platforms.")
69 changes: 69 additions & 0 deletions lsports/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Originally sourced from pySerial. https://github.com/pyserial/pyserial
# (C) 2011-2015 Chris Liechti <[email protected]>
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations

import argparse
import re
import sys
from collections.abc import Generator

from lsports import PortInfo, comports


def grep(
regexp: str | re.Pattern[str], include_links: bool = False
) -> Generator[PortInfo, None, None]:
"""Search for ports using a regular expression.
Port name, description and hardware ID are searched.
Returns:
An iterable that returns the same tuples as :func:`comport` would do.
"""
r = re.compile(regexp, re.I)
for info in comports(include_links):
if r.search(info.device) or r.search(info.description) or r.search(info.hwid):
yield info


def main() -> int:
parser = argparse.ArgumentParser(prog="lsports", description="Serial ports enumeration.")
parser.add_argument("regexp", nargs="?", help="Only show ports that match this regex")
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument("-v", "--verbose", action="store_true", help="Show more messages")
verbosity.add_argument("-q", "--quiet", action="store_true", help="Suppress all messages")
parser.add_argument("-n", type=int, help="Only output the N-th entry")
parser.add_argument(
"-s",
"--include-links",
action="store_true",
help="Include entries that are symlinks to real devices",
)
args = parser.parse_args()

hits = 0
# get iterator w/ or w/o filter
if args.regexp:
if not args.quiet:
print(f"Filtered list with regexp: {args.regexp!r}", file=sys.stderr)
devices = sorted(grep(args.regexp, include_links=args.include_links))
else:
devices = sorted(comports(include_links=args.include_links))
# list them
for n, device in enumerate(devices, 1):
if args.n is None or args.n == n:
print(f"{device.device}")
if args.verbose:
msg = f" desc: {device.description}\n hwid: {device.hwid}"
if device.product:
msg += f"\n prod: {device.product}"
print(msg)
hits += 1
if not args.quiet:
print({0: "No ports", 1: "1 port"}.get(hits, f"{hits} ports") + " found", file=sys.stderr)
return 0


if __name__ == "__main__":
sys.exit(main())
Loading

0 comments on commit 814fcb5

Please sign in to comment.