【问题标题】:How to RegEx value from terminal output如何从终端输出中获取 RegEx 值
【发布时间】:2019-08-20 10:37:51
【问题描述】:

我正在尝试从终端输出中获取时间值。

import os
import re

cmd = os.popen('time Open /Applications/TextEdit.app').read()

time = re.search("real  [0-9]{1}", cmd)

print(time)

但是找不到。

输出

real    0m0.042s
user    0m0.015s
sys 0m0.013s
None

我什至不能得到 0。我怎样才能得到 0.042 作为我的时间变量?

【问题讨论】:

  • time = re.search("^real\s+(\S+)$", cmd, re.M).group(1)
  • 我得到“AttributeError: 'NoneType' 对象没有属性 'group'”
  • 你的outputcmd的内容吗?请发布cmd的内容
  • @WiktorStribiżew 您显然是一位不需要提高声誉的正则表达式大师。但是,通过实际创建答案而不是仅仅发表评论以便可以接受并且标记为已回答的问题,您不会帮这个网站一个忙吗?
  • real 0m0.045s user 0m0.016s sys 0m0.013s Traceback (most recent call last): File "demotest", line 7, in <module> time = re.search("^real\s+(\S+)$", cmd, re.M).group(1) AttributeError: 'NoneType' object has no attribute 'group'

标签: python regex macos terminal


【解决方案1】:

问题是time 默认打印在stderr 上,而对os.popen 的调用只保存cmd 中的stdout。因此,我建议执行以下操作:

from subprocess import PIPE, Popen

p = Popen("time Open /Applications/TextEdit.app", shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
time = re.search("^real\s+(\S+)$", stderr, re.M).group(1)

感谢 @Wiktor Stribiżew 提供正则表达式

【讨论】:

    【解决方案2】:

    试试这样:

    time = re.search("real    \d+m\d+.\d+s", cmd)
    

    【讨论】:

    • “真实”和时间分量之间的空格数错误,不是吗?你测试过这个吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2013-01-25
    • 2013-08-18
    • 2011-05-23
    • 2013-03-22
    相关资源
    最近更新 更多