1

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).

MikeWade
  • 84
  • 1
  • 7
  • 2
    It's a mistake to use the Python interactive console as a long-term shell environment. Use it for testing Python statements; attempting to use it as a general purpose shell is inviting an endless series of frustrations like this. – bignose May 22 '14 at 06:06
  • Use `re` to do pattern match in python or write the log to a temp file to use `grep`. – WKPlus May 22 '14 at 06:11
  • ipython has way to handle grepping output from a shell/system command. [Example post](http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/shell.html#string-lists) from ipython's documentation. I'm hoping someone has bent this ability to be easier to leverage, and not limited to the contents of the object. – MikeWade May 22 '14 at 06:40

2 Answers2

2

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]
bignose
  • 30,281
  • 14
  • 77
  • 110
  • I think 'myPhone.print_call_log()' is a `'\n'` separated string and can use `split('\n')` to convert it to a sequence. – WKPlus May 22 '14 at 06:13
0

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:

Docs:

Edit:

Based on comment by glglgl

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

Community
  • 1
  • 1
jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • Rather than `results = subprocess.check_output('echo \''+myPhone.print_call_log()+'\' | grep 555', shell=True)`, a combination of `stdin=stubprocess.PIPE` and `.communicate()` would be more appropriate... but then, you can omit the subprocess altogether and perform the search on your own. – glglgl May 22 '14 at 06:22
  • BTW, what do you do if there are any `'` in your `print_call_log()` output? If you replace them by `'\''`, you should be fine. But "elegant" is not quite the right word for this... – glglgl May 22 '14 at 06:23