简体   繁体   English

用于输出的fileinput.input()的Python模拟是什么?

[英]What's the Python analogue of fileinput.input() for output?

fileinput.input() allows to simply loop over all lines in either a list of input files provided via sys.argv[1:] or sys.stdin if the former is empty. fileinput.input()允许简单地循环遍历通过sys.argv[1:]sys.stdin提供的输入文件列表中的所有行(如果前者为空)。

Is there a similarly simple way to output to the last argument if given and sys.stdout otherwise? 是否有类似的简单方法输出到最后一个参数(如果给定),否则输出到sys.stdout

You can use the argparse module and add a commandline argument like this: 您可以使用argparse模块并添加如下命令行参数:

parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
                    default=sys.stdout)

You can check if the final argument is a file, in which case it is an input so set the output to sys.stdout , otherwise open a new file with that name as output and remove it from sys.argv . 您可以检查最终参数是否是文件,在这种情况下,它是输入,因此将输出设置为sys.stdout ,否则打开一个具有该名称的新文件作为输出并将其从sys.argv删除。

Alternatively just use sys.stdout and let your users use > filename to store to a file. 或者,只需使用sys.stdout并让您的用户使用> filename来存储到文件中。

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

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