pylspci/pylspci/parsers/simple.py

91 lines
2.4 KiB
Python
Raw Normal View History

import argparse
import shlex
2020-11-29 18:17:36 +00:00
from typing import Iterable, List, Union
from cached_property import cached_property
from pylspci.device import Device
from pylspci.fields import NameWithID, Slot, hexstring
from pylspci.parsers.base import Parser
2019-07-10 17:02:55 +00:00
class SimpleParser(Parser):
2019-07-10 18:54:15 +00:00
"""
A parser for lspci -mm.
"""
2019-07-06 13:51:34 +00:00
@cached_property
2019-07-10 17:02:55 +00:00
def _parser(self) -> argparse.ArgumentParser:
2019-07-06 13:51:34 +00:00
p = argparse.ArgumentParser()
p.add_argument(
'slot',
type=Slot,
)
2019-07-06 13:51:34 +00:00
p.add_argument(
2019-07-06 13:13:27 +00:00
'cls',
type=NameWithID,
)
2019-07-06 13:51:34 +00:00
p.add_argument(
'vendor',
type=NameWithID,
)
2019-07-06 13:51:34 +00:00
p.add_argument(
'device',
type=NameWithID,
)
2019-07-06 13:51:34 +00:00
p.add_argument(
'subsystem_vendor',
type=NameWithID,
)
2019-07-06 13:51:34 +00:00
p.add_argument(
'subsystem_device',
type=NameWithID,
)
2019-07-06 13:51:34 +00:00
p.add_argument(
'-r',
type=hexstring,
nargs='?',
dest='revision',
)
2019-07-06 13:51:34 +00:00
p.add_argument(
'-p',
type=hexstring,
nargs='?',
dest='progif',
)
2019-07-06 13:51:34 +00:00
return p
2019-09-06 21:09:50 +00:00
def parse(
self,
data: Union[str, Iterable[str], Iterable[Iterable[str]]],
) -> List[Device]:
2019-07-10 18:54:15 +00:00
"""
Parse a multiline string or a list of single-line strings
from lspci -mm into devices.
2019-09-06 21:09:50 +00:00
:param data: A string holding multiple devices,
a list of strings, one for each device,
or a list of lists of strings, one list for each device, with
each list holding each part of the device output.
:type data: str or Iterable[str] or Iterable[Iterable[str]]
2019-07-10 18:54:15 +00:00
:return: A list of parsed devices.
:rtype: List[Device]
"""
2019-07-10 17:02:55 +00:00
if isinstance(data, str):
data = data.splitlines()
return list(map(self.parse_line, data))
2019-08-03 22:53:16 +00:00
def parse_line(self, args: Union[str, Iterable[str]]) -> Device:
2019-07-10 18:54:15 +00:00
"""
Parse a single line from lspci -mm into a single device, either
as the line or as a list of fields.
:param args: Line or list of fields to parse from.
2019-08-03 22:53:16 +00:00
:type args: str or Iterable[str]
2019-07-10 18:54:15 +00:00
:return: A single parsed device.
:rtype: Device
"""
if isinstance(args, str):
args = shlex.split(args)
2019-07-10 17:02:55 +00:00
return Device(**vars(self._parser.parse_args(args)))