微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当从grep 子进程中出来时,如何将经过的秒数附加到每一行的前面? 更新

如何解决当从grep 子进程中出来时,如何将经过的秒数附加到每一行的前面? 更新

我试图将经过的秒数附加到从 grep 出来的每一行中,但我遇到了一些问题。

一个挑战是我想在 top,grep 进程在后台运行时运行其他代码。 (所以实现必须是非阻塞的)

目前,由于 SO 上的另一个答案,我已经能够附加当前时间。在我的示例代码中,我使用的是“perl”,但它不需要,尽管我不能使用 gawk/ts 或任何其他在 MacOS 上不认的实用程序/命令。

顶部输出示例

1227  Google Chrome He 0.0  00:06.59 13    1    151    58M   0B    51M   793  793  sleeping *0[5]     0.00000 0.00000    502 35702   2182  20972   10027   34224  

所需输出写入文本文件的示例(假设过去了 1.59 秒)

1.59 1227  Google Chrome He 0.0  00:06.59 13    1    151    58M   0B    51M   793  793  sleeping *0[5]     0.00000 0.00000    502 35702   2182  20972   10027   34224 

文件中的下一行应该有另一个 top 输出,稍后时间(假设下一个 top 命令从初始开始时间起 2.13 秒后从缓冲区中出来)

2.13 1227  Google Chrome He 0.0  00:06.59 13    1    151    58M   0B    51M   793  793  sleeping *0[5]     0.00000 0.00000    502 35702   2182  20972   10027   34224

到目前为止我的代码

from timeit import default_timer as timer

start_time = timer()

f = open('file.txt','w')

top_proc = subprocess.Popen(['top'],stdout=subprocess.PIPE)
grep_proc = subprocess.Popen(['grep','--line-buffered',' Chrome'],stdin=top_proc.stdout,stdout=subprocess.PIPE)

# Somehow append elapsed time since start_time to the grep output with this other process (it would be appending `timer() - start_time`) 
# Currently it just appends the current time
perl_proc = subprocess.Popen(['perl','-pe','use POSIX strftime; print strftime "%H:%M:%s ",localtime'],stdin=grep_proc.stdout,stdout=f)

# Other code that runs for indefinite amount of time
other_code()

top_proc.send_signal(signal.SIGINT)

top_proc.wait()
grep_proc.wait()
perl_proc.wait()
f.close()

我使用 timeit 模块是因为根据我的研究,它更准确,而且我的代码是用于对 Chrome 进程的内存使用情况进行基准测试的脚本的一部分。我尝试查看 perl 命令,但很难找到任何示例或类似用例。

有什么方法可以重新调整我的 perl 子进程以附加经过的时间?或者我可以通过哪些其他方式实现我的目标?

更新

我尝试执行 perl_proc = subprocess.Popen(['perl','print "' + str(time.time() - start_time) + '" '],stdout=f),但它似乎只给我初始行的经过时间。

解决方法

为什么要使用子进程来完成 Python 中很少可用的事情?

import time
import subprocess

start_time = time.time()

f = open('file.txt','w')

top_proc = subprocess.Popen(['top'],stdout=subprocess.PIPE)
for line in top_proc.stdout:
    if b'Chrome' in line:
        print( "%.3f" % (time.time() - start_time),line )

然而,top 并非设计为由此调用。您的行将包含终端控制字符。

顺便说一下,awk 肯定在 MacOS 中可用,就像完整的普通 Unix 命令集一样。

,

GNU ts 软件包中的程序 moreutils(时间戳)完全符合您的要求。

示例:

for i in a b c d e; do echo $i; sleep 1; done | ts -s %.s

印刷品

0.000016 a
0.944115 b
1.974076 c
3.002769 d
4.031955 e

但是,我同意 Tim Roberts:在 python 中进行时间戳将是要走的路。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。