从文件中读取,或标准输入 [英] Read from File, or STDIN
问题描述
我编写了一个命令行实用程序,它使用 getopt 来解析命令行上给出的参数.我还希望文件名是一个可选参数,例如它在 grep、cut 等其他实用程序中.所以,我希望它具有以下用法
I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage
tool -d character -f integer [filename]
如何实现以下内容?
- 如果给出了文件名,则从文件中读取.
- 如果没有给出文件名,则从 STDIN 读取.
推荐答案
简单来说:
import sys
# parse command line
if file_name_given:
inf = open(file_name_given)
else:
inf = sys.stdin
此时您将使用 inf
从文件中读取.根据是否给定文件名,这将从给定的文件或标准输入读取.
At this point you would use inf
to read from the file. Depending on whether a filename was given, this would read from the given file or from stdin.
当你需要关闭文件时,你可以这样做:
When you need to close the file, you can do this:
if inf is not sys.stdin:
inf.close()
然而,在大多数情况下,如果你完成了关闭 sys.stdin
是无害的.
However, in most cases it will be harmless to close sys.stdin
if you're done with it.
这篇关于从文件中读取,或标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!