2024-05-16 02:41:20 发布
网友
在Python中编写面向文本的命令行程序时,我通常希望读取在命令行上传递的所有文件,或者(XOR)标准输入(如Unixcat所做的,或者Perl的<>)。所以,我说
cat
<>
if len(args) == 0: # result from optparse input = sys.stdin else: input = itertools.chain(*(open(a) for a in args))
这是Python式的做法,还是我错过了图书馆的某个部分?
你需要fileinput。
标准用例是:
import fileinput for line in fileinput.input(): process(line)
见
How do you read from stdin in Python?
在Python 3中,^{} handles filetype objects非常好。它是一个非常强大的模块,文档中有许多示例,因此很容易快速编写所需的代码。(多么顽皮!)
您还可以从thisStackOverflow问题中受益,这个问题是关于使用argparse从stdin进行可选读取的。
argparse
你需要fileinput。
标准用例是:
见
How do you read from stdin in Python?
在Python 3中,^{} handles filetype objects 非常好。它是一个非常强大的模块,文档中有许多示例,因此很容易快速编写所需的代码。(多么顽皮!)
您还可以从thisStackOverflow问题中受益,这个问题是关于使用
argparse
从stdin进行可选读取的。相关问题 更多 >
编程相关推荐