[英]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: 换一种说法:
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,那就试试吧。
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.