使用optpars将stdin和stdout重定向到python中的文件的一致方法

2024-03-29 15:51:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有十几个程序可以通过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的人的引用。这是一个很好的一致性解决方案还是我忽略了一些更好或更值得期待的东西?


Tags: the代码adddefaultparseroutputisstdin
2条回答

对于输入文件,可以使用^{}模块。它遵循输入文件的通用约定:如果没有给定文件或文件名为“-”,则读取stdin,否则从命令行给定的文件中读取。

不需要-f--file选项。如果你的程序总是需要一个输入文件,那么它不是一个选项。

-o--output用于指定the output file name in various programs

optparse

#!/usr/bin/env python
import fileinput
import sys
from optparse import OptionParser

parser = OptionParser()
parser.add_option('-o', '--output',
    help='Specifies the output file.  The default is stdout.')
options, files = parser.parse_args()
if options.output and options.output != '-':
   sys.stdout = open(options.output, 'w')

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

argparse

^{}模块允许您显式指定文件作为参数:

#!/usr/bin/env python
import fileinput
import sys
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('files', nargs='*', help='specify input files')
group = parser.add_mutually_exclusive_group()
group.add_argument('-o', '--output', 
    help='specify the output file.  The default is stdout')
group.add_argument('-i', '--inplace', action='store_true',
    help='modify files inplace')
args = parser.parse_args()

if args.output and args.output != '-':
   sys.stdout = open(args.output, 'w')

for line in fileinput.input(args.files, inplace=args.inplace):
    process(line)

注意:我在第二个示例中添加了--inplace选项:

$ python util-argparse.py --help
usage: util-argparse.py [-h] [-o OUTPUT | -i] [files [files ...]]

positional arguments:
  files                 specify input files

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        specify the output file. The default is stdout
  -i, --inplace         modify files inplace

如果您可以使用^{}(即Python 2.7+),则它具有对所需内容的内置支持:直接从^{} doc

The FileType factory creates objects that can be passed to the type argument of ArgumentParser.add_argument(). Arguments that have FileType objects as their type will open command-line arguments […] FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects.

所以我的建议是

import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'),
    help="Specifies the input file")
parser.add_argument('output', type=argparse.FileType('w'),
    help="Specifies the output file")
args = parser.parse_args(sys.argv[1:])

# Here you can use your files
text = args.file.read()
args.output.write(text)
# … and so on

那你就可以了

> python spam.py file output 

file读取并输出到output,或

> echo "Ni!" | python spam.py - output  

读取"Ni!"并输出到output,或

> python spam.py file -

这很好,因为使用-作为相关流 is a convention that a lot of programs use。如果要指出它,请将其添加到help字符串中。

  parser.add_argument('file', type=argparse.FileType('r'),
    help="Specifies the input file, '-' for standard input")

作为参考,使用信息将是

> python spam.py -h
usage: [-h] file output

positional arguments:
  file        Specifies the input file, '-' for standard input
  output      Specifies the output file, '-' for standard output

optional arguments:
  -h, --help  show this help message and exit

相关问题 更多 >