python - 使用python的shell命令数组输出到csv列?
问题描述
以下是“lastcomm”bash 命令的输出(日志)。
python3 root __ 0.34 secs Tue Dec 11 09:06
python3 root __ 0.32 secs Tue Dec 11 09:06
python3 root __ 0.36 secs Tue Dec 11 09:06
cron SF root __ 0.00 secs Tue Dec 11 09:06
sh S root __ 0.00 secs Tue Dec 11 09:06
python3 root __ 0.29 secs Tue Dec 11 09:06
cron SF root __ 0.00 secs Tue Dec 11 09:06
sh S root __ 0.00 secs Tue Dec 11 09:06
python3 root __ 0.30 secs Tue Dec 11 09:06
cron SF root __ 0.00 secs Tue Dec 11 09:06
sh S root __ 0.00 secs Tue Dec 11 09:06
python3 root __ 0.31 secs Tue Dec 11 09:06
cron SF root __ 0.00 secs Tue Dec 11 09:06
sh S root __ 0.00 secs Tue Dec 11 09:06
python3 root __ 0.28 secs Tue Dec 11 09:06
sh root __ 0.00 secs Tue Dec 11 09:06
uname root __ 0.00 secs Tue Dec 11 09:06
我通过在 python 中使用以下代码得到了这个。
import subprocess
file_ = open("pacct.csv", "w")
subprocess.Popen(['lastcomm'], stdout=file_)
我想按列分隔输出(日志)并使用列结构保存 csv 文件。
但是上面的代码只保存了完全相同的输出(日志)的纯文本。输出的分隔符(分隔符)不是“制表符”而是“不同大小的空间”,因此按列拆分列表确实很困难。
如何按列拆分输出(日志)的元素并使用python3保存具有列结构的csv文件?
期望的结果:(如果我得到如下的列表结构,我会将其转换为列结构-csv 文件。)
[['python3', '', 'root', '_', '0.34 secs Tue Dec 11 09:06'],
['python3', '', 'root', '_', '0.32 secs Tue Dec 11 09:06'],
['python3', '', 'root', '_', '0.36 secs Tue Dec 11 09:06'],
['cron', 'SF', 'root', '_', '0.00 secs Tue Dec 11 09:06'],
['sh', 'S', 'root', '_', '0.00 secs Tue Dec 11 09:06'], ...]
非常感谢。
解决方案
从手册页
For each entry the following information is printed:
+ command name of the process
+ flags, as recorded by the system accounting routines:
S -- command executed by super-user
F -- command executed after a fork but without a following
exec
C -- command run in PDP-11 compatibility mode (VAX only)
D -- command terminated with the generation of a core file
X -- command was terminated with the signal SIGTERM
+ the name of the user who ran the process
+ time the process started
很明显 lastcomm 提供command
, flags
,user
和time
这"__"
只是占位符。你可以通过row.split("__")[1].lstrip(" ").rstrip("\n")
for command
,从行开始搜索字符,直到出现前两个空格
并user
做类似但相反的事情。
将行的其余部分包含一个空格是flags
推荐阅读
- websphere - Websphere 配置文件路径在节点创建期间已存在
- c - 我在程序 C 中出现 Time Limit Exceeded 错误。如何克服它?
- php - 控制器中的非法字符串偏移“antrian_seminggu”(codeigniter)
- php - 根据 woocomerce 中的客户国家代码显示价格
- google-cloud-platform - 优化 Dataproc 集群启动时间
- node.js - 为什么 setInterval 不能用于生产?
- rest - 使用 last.fm API 维护 HTTP 缓存
- java - Arrays asList() accepts instance of class
- python-3.x - how to minimize the massive message delay paho mqtt
- python - Regarding Acuracy is low after Training the new data with old Trained weight file