![](/img/trans.png)
[英]Is there a way to save both python stdout and stdin to file using only bash?
[英]Consistent way to redirect both stdin & stdout to files in python using optparse
我有十幾個可以通過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的人的引用。 這是一個很好的一致解決方案還是我忽略了更好或更期望的事情?
對於輸入文件,您可以使用fileinput
模塊。 它遵循輸入文件的通用約定:如果沒有給定文件或文件名是' - ',它將讀取stdin,否則它將從命令行給出的文件中讀取。
-f
和--file
選項不需要。 如果您的程序總是需要輸入文件,那么它不是一個選項。
-o
和--output
用於指定各種程序中的輸出文件名 。
#!/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
如果你可以使用argparse
(即Python 2.7+),它內置了對你想要的支持:直接來自argparse
doc
FileType
工廠創建可以傳遞給ArgumentParser.add_argument()
的type參數的對象。 將FileType
對象作為其類型的參數將打開命令行參數[...]FileType
對象理解偽參數' - '並自動將其轉換為sys.stdin以獲取可讀的FileType
對象,並將sys.stdout
為可寫的FileType
對象。
所以我的建議是簡單地使用
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 -
...
這很好,因為使用-
對於相關流是許多程序使用的約定 。 如果要指出它,請將其添加到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.