我有十几个程序可以通过stdin或一个选项接受输入,我希望以类似的方式实现相同的输出特性。
optparse代码如下所示:
parser.add_option('-f', '--file',
default='-',
help='Specifies the input file. The default is stdin.')
parser.add_option('-o', '--output',
default='-',
help='Specifies the output file. The default is stdout.')
其他适用的代码如下所示:
if opts.filename == '-':
infile = sys.stdin
else:
infile = open(opts.filename, "r")
if opts.output == '-':
outfile = sys.stdout
else:
outfile = open(opts.output, "w")
这段代码工作得很好,我喜欢它的简单性——但是我还没有找到任何使用默认值“-”作为输出来指示stdout的人的引用。这是一个很好的一致性解决方案还是我忽略了一些更好或更值得期待的东西?
对于输入文件,可以使用^{} 模块。它遵循输入文件的通用约定:如果没有给定文件或文件名为“-”,则读取stdin,否则从命令行给定的文件中读取。
不需要
-f
和--file
选项。如果你的程序总是需要一个输入文件,那么它不是一个选项。-o
和--output
用于指定the output file name in various programs。optparse
argparse
^{} 模块允许您显式指定文件作为参数:
注意:我在第二个示例中添加了
--inplace
选项:如果您可以使用^{} (即Python 2.7+),则它具有对所需内容的内置支持:直接从^{} doc
所以我的建议是
那你就可以了
从
file
读取并输出到output
,或读取
"Ni!"
并输出到output
,或这很好,因为使用
-
作为相关流 is a convention that a lot of programs use。如果要指出它,请将其添加到help
字符串中。作为参考,使用信息将是
相关问题 更多 >
编程相关推荐