是否有现成方案将stdin内容解析为命令行位置参数?
如何通过stdin传递位置参数,避免重复造轮子?
我希望能通过stdin传递位置参数,自己已经写了一个argparse.Action的子类实现了这个功能,但不想重复造轮子,想问有没有现成的内置或第三方方案,可以自动处理以连字符-作为参数集来源的场景?
我的实现代码如下:
class ExtendStdin(Action): def __call__( self, parser: ArgumentParser, namespace: Namespace, values: Sequence[str | Path], option_string: Optional[str] = None, ) -> None: if "-" in values: if len(values) == 1: content = sys.stdin.read() sep = "\0" if "\0" in content else "\n" values = list(map(existing_filepath, content.split(sep))) else: raise ValueError("Specification of both stdin & paths is not allowed.") setattr(namespace, self.dest, values)
其中existing_filepath是用于检查文件路径是否存在的函数。
我知道argparse的FileType特性,它可以把连字符转换为默认的stdin或stdout,但这个特性是把连字符当成单个类文件参数,而不是参数集的来源。
更新 2023.09.15
本问题聚焦于argparse的扩展或工具包,用于增强参数解析的辅助功能。我知晓shlex包可以处理字符串与shell参数集的互转,但本问题并非关于如何拆分标准输入流。
内容的提问来源于stack exchange,提问作者Vovin
相关产品推荐
相关产品推荐

