Python fileinput 模块:命令行工具利器

栏目: IT技术 · 发布时间: 6年前

内容简介:命令行工具经常要处理从在需要一个工具,如

命令行 工具 经常要处理从 stdin 或文件读取输入, fileinput 模块让我们很轻松就能实现。

示例需求

tail -f 看日志的时候,如果在某一行卡了很长时间,往往我们想看到底花了多长时间。因此希望有一个工具,能在每行日志前加上接收时的时间戳。例如:

$ tail -f xxx.log
some good thing happend
some good thing happend
some bad thing happend

需要一个工具,如 timed.py :

$ tail -f xxx.log | timed.py
[2020-03-27 10:41:13.514709] some good thing happend
[2020-03-27 10:41:13.525803] some good thing happend
[2020-03-27 10:41:13.630232] some bad thing happend

这样就能知道花了多长时间。

示例实现

有了 fileinput 处理标准输入,只需要 4 行:

from datetime import datetime
import fileinput
for line in fileinput.input():
    print(f'[{datetime.now()}] {line}', end='')

更多特性

其实如果只是从标准输入读取,也不麻烦,上面的例子可以写成:

from datetime import datetime
import sys
for line in sys.stdin:
    print(f'[{datetime.now()}] {line}', end='')

fileinput 同时还能处理参数( sys.args )中的文件:

$ timed.py <file1> <file2>
$ timed.py <file1> - # 读取文件 file1 后等待标准输入

对于传统的行处理程序来说,十分便利


以上所述就是小编给大家介绍的《Python fileinput 模块:命令行工具利器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms for Image Processing and Computer Vision

Algorithms for Image Processing and Computer Vision

Parker, J. R. / 2010-12 / 687.00元

A cookbook of algorithms for common image processing applications Thanks to advances in computer hardware and software, algorithms have been developed that support sophisticated image processing with......一起来看看 《Algorithms for Image Processing and Computer Vision》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试