gpt4 book ai didi

Python 从命令行参数或标准输入中读取

转载 作者:太空狗 更新时间:2023-10-29 20:11:42 24 4
gpt4 key购买 nike

在用 Python 编写面向文本的命令行程序时,我经常想读取命令行上传递的所有文件,或者 (XOR) 标准输入(如 Unix cat 或 Perl 的 <> )。所以,我说

if len(args) == 0:  # result from optparse
input = sys.stdin
else:
input = itertools.chain(*(open(a) for a in args))

这是执行此操作的 Pythonic 方式,还是我错过了库的某些部分?

最佳答案

你需要fileinput .

标准用例是:

import fileinput
for line in fileinput.input():
process(line)

关于Python 从命令行参数或标准输入中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5675938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com