2020年8月13日 / 568次阅读 / Last Modified 2020年8月13日
argparse模块
argparse.FileType参数出现在add_argument函数的type参数中,用来给命令行参数指定一个文件流。比较特别的是,这个文件流可以指向sys.stdin和sys.stdout,用来获取通过命令行管道来的数据,或者向sys.stdout输出数据。
上一段代码:
$ cat arg.py
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?',
type=argparse.FileType(),
help='give me a file here, i open it and reture to you',
default=sys.stdin)
parser.add_argument('outfile', nargs='?',
type=argparse.FileType('w'),
help='give me a file here, i write it for you with in file',
default=sys.stdout)
args = parser.parse_args()
with args.infile as f, args.outfile as g:
g.write(f.read())
这段代码实现将infile中的内容copy输出到outfile中去,infile默认是sys.stdin,outfile默认是sys.stdout,即如果不输入参数,程序将从sys.stdin读取数据,然后写到sys.stdout中去。
运行效果如下:
$ echo 'abcde12345' > t1.txt
$ python3.8 arg.py t1.txt t2.txt
$ cat t2.txt
abcde12345
$ echo -e 'abcde\n12345' | python3.8 arg.py
abcde
12345
$ python3.8 arg.py < t1.txt
abcde12345
$ python3.8 arg.py kkkkk.txt
usage: arg.py [-h] [infile] [outfile]
arg.py: error: argument infile: can't open 'kkkkk.txt': [Errno 2] No such file or directory: 'kkkkk.txt'
用argparse.FileType,除了可以实现输入参数为文件外(遇到不存在的文件,会提示错误,这样就不用自己去判断文件是否存在了),还可以很好的实现通过命令行管道来接收数据。(这是我之前用其它方式实现的python程序从管道接收数据)
-- EOF --
本文链接:https://www.pynote.net/archives/2353
前一篇:with file的用法
后一篇:Email批量发送工资条的方案
©Copyright 麦新杰 Since 2019 Python笔记