简体   繁体   English

使用argparse从stdin或输入文件中读取

[英]Read from stdin or input file with argparse

I'd like to use argparse to read from either stdin or an input file. 我想使用argparse 无论从读取stdin 输入文件。 In other words: 换一种说法:

  • If an input file is given, read that. 如果给出了输入文件,请阅读。
  • If not, read from stdin only if it's not the terminal. 如果不是, 只有当它不是终端时才从stdin读取。 (ie a file is being piped in) (即正在输入文件)
  • If neither of these criteria are satisfied, signal to argparse that the inputs aren't correct. 如果这些标准都不满足,则向argparse发出输入信号不正确的信号。

I'm asking for behavior similar to what's described in this question , but I want argparse to recognize no file as a failed input. 我要求的行为类似于此问题中描述的行为,但我希望argparse不会将文件识别为失败的输入。

Using the information from the question you linked to, what about using sys.stdin.isatty() to check if the instance your program is being run is part of a pipeline, if not, read from input file, otherwise read from stdin . 使用您链接到的问题中的信息,使用sys.stdin.isatty()检查程序运行的实例是否是管道的一部分,如果没有,则从输入文件读取,否则从stdin读取。 If the input file does not exist or stdin is empty throw an error. 如果输入文件不存在或stdin为空则抛出错误。

Hope that helped. 希望有所帮助。

I would recommend just settings nargs='?' 我建议只设置nargs='?' and then handling the case of a Nonetype separately. 然后单独处理Nonetype的情况。 According to the official documentation , "FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects" . 根据官方文档“FileType对象理解伪参数' - '并自动将其转换为sys.stdin以获取可读的FileType对象,并将sys.stdout转换为可写的FileType对象” So just give it a dash if you want stdin. 如果你想要stdin,那就试试吧。

Example

import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('inputfile', nargs='?', type=argparse.FileType('r'))
if not inputfile:
    sys.exit("Please provide an input file, or pipe it via stdin")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM