Using grep from python console

流过昼夜 提交于 2021-02-08 08:59:26

问题


Using python how can I make this happen?

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

The only thing close that I've seen is using "ipython console", assigning output to a variable, and then using a .grep() function on that variable. This is not really what I'm after. I want pipes and grepping on anything in the output (including errors/info).


回答1:


Python's interactive REPL doesn't have grep, nor process pipelines, since it's not a Unix shell. You need to work with Python objects.

So, assuming the return value of myPhone.print_call_log is a sequence:

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



回答2:


What about something like this.

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

Or:

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

It is hard to tell without knowing what the return type of myPhone.print_call_log(). Is it a generator, or does it return a list? Or a string?

Related Questions:

  • piping in shell via Python subprocess module
  • Assign output of os.system to a variable and prevent it from being displayed on the screen

Docs:

  • https://docs.python.org/2/library/subprocess.html#subprocess.check_output

Edit:

Based on comment by glglgl

Something like this might be more appropriate as written by glglgl:

  • https://stackoverflow.com/a/10363929/2026508


来源:https://stackoverflow.com/questions/23798617/using-grep-from-python-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!