You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否有现成方案将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:02:15