从 python 控制台使用 grep

问题描述 投票:0回答:3

使用 python 我怎样才能做到这一点?

python_shell$>  print myPhone.print_call_log()  |  grep 555

我见过的唯一接近的事情是使用“ipython console”,将输出分配给变量,然后在该变量上使用 .grep() 函数。这并不是我真正想要的。我想要管道和 grep 输出中的任何内容(包括错误/信息)。

python grep pipe ipython
3个回答
2
投票

Python 的交互式 REPL 没有

grep
,也没有进程管道,因为它不是 Unix shell。您需要使用 Python 对象。

因此,假设

myPhone.print_call_log
的返回值是一个序列:

call_log_entries = myPhone.print_call_log()
entries_containing_555 = [
        entry for entry in call_log_entries
        if "555" in entry]

0
投票

这样的事情怎么样?

import subprocess
results = subprocess.check_output('cat /path/to/call_log.txt | grep 555', shell=True)
print(results)

或者:

import subprocess
string = myPhone.print_call_log().replace("\'","\\'")
results = subprocess.check_output('echo \''+string+'\' | grep 555', shell=True)
print(results)

在不知道 myPhone.print_call_log() 的返回类型的情况下很难判断。它是一个生成器,还是返回一个列表?还是字符串?

相关问题:

文档:

编辑:

基于 glglgl 的评论

glglgl 写的这样的东西可能更合适:


0
投票

我知道在这里回答有点晚了,但我刚刚完成了一个简单的项目来实现这一点!

安装

pip install greps

用法

%load_ext greps

In [1]: {i:i for i in range(3)}
Out[1]: 
{0: 0,
 1: 1,
 2: 2,
}
 
In [2]: %greps 1
Out[2]: ' 1: 1,\n'

您可以在存储库中找到更多信息:https://github.com/royreznik/greps

© www.soinside.com 2019 - 2024. All rights reserved.