内容简介:命令行工具经常要处理从在需要一个工具,如
命令行 工具 经常要处理从 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 模块:命令行工具利器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Python fileinput 模块:命令行工具利器
- 网络分析利器wireshark命令版:Apache Spot中tshark模块(3)
- JMockit:单元测试利器
- 利器+
- Go 调试利器:delve
- go调试利器-delve
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web Design Handbook
Baeck, Philippe de 编 / 2009-12 / $ 22.54
This non-technical book brings together contemporary web design's latest and most original creative examples in the areas of services, media, blogs, contacts, links and jobs. It also traces the latest......一起来看看 《Web Design Handbook》 这本书的介绍吧!